blob: 689fe5c73ba0e356b0fb4af7658b96d9092c4efa [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
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002475/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002476 * Ensure the correct coordinate spaces are used by InputDispatcher.
2477 *
2478 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2479 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2480 * space.
2481 */
2482class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2483public:
2484 void SetUp() override {
2485 InputDispatcherTest::SetUp();
2486 mDisplayInfos.clear();
2487 mWindowInfos.clear();
2488 }
2489
2490 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2491 gui::DisplayInfo info;
2492 info.displayId = displayId;
2493 info.transform = transform;
2494 mDisplayInfos.push_back(std::move(info));
2495 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2496 }
2497
2498 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2499 mWindowInfos.push_back(*windowHandle->getInfo());
2500 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2501 }
2502
2503 // Set up a test scenario where the display has a scaled projection and there are two windows
2504 // on the display.
2505 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2506 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2507 // respectively.
2508 ui::Transform displayTransform;
2509 displayTransform.set(2, 0, 0, 4);
2510 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2511
2512 std::shared_ptr<FakeApplicationHandle> application =
2513 std::make_shared<FakeApplicationHandle>();
2514
2515 // Add two windows to the display. Their frames are represented in the display space.
2516 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002517 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2518 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002519 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2520 addWindow(firstWindow);
2521
2522 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002523 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2524 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002525 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2526 addWindow(secondWindow);
2527 return {std::move(firstWindow), std::move(secondWindow)};
2528 }
2529
2530private:
2531 std::vector<gui::DisplayInfo> mDisplayInfos;
2532 std::vector<gui::WindowInfo> mWindowInfos;
2533};
2534
2535TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2536 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2537 // Send down to the first window. The point is represented in the display space. The point is
2538 // selected so that if the hit test was done with the transform applied to it, then it would
2539 // end up in the incorrect window.
2540 NotifyMotionArgs downMotionArgs =
2541 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2542 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2543 mDispatcher->notifyMotion(&downMotionArgs);
2544
2545 firstWindow->consumeMotionDown();
2546 secondWindow->assertNoEvents();
2547}
2548
2549// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2550// the event should be treated as being in the logical display space.
2551TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2552 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2553 // Send down to the first window. The point is represented in the logical display space. The
2554 // point is selected so that if the hit test was done in logical display space, then it would
2555 // end up in the incorrect window.
2556 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2557 PointF{75 * 2, 55 * 4});
2558
2559 firstWindow->consumeMotionDown();
2560 secondWindow->assertNoEvents();
2561}
2562
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002563// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2564// event should be treated as being in the logical display space.
2565TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2566 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2567
2568 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2569 ui::Transform injectedEventTransform;
2570 injectedEventTransform.set(matrix);
2571 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2572 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2573
2574 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2575 .displayId(ADISPLAY_ID_DEFAULT)
2576 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2577 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2578 .x(untransformedPoint.x)
2579 .y(untransformedPoint.y))
2580 .build();
2581 event.transform(matrix);
2582
2583 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2584 InputEventInjectionSync::WAIT_FOR_RESULT);
2585
2586 firstWindow->consumeMotionDown();
2587 secondWindow->assertNoEvents();
2588}
2589
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002590TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2591 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2592
2593 // Send down to the second window.
2594 NotifyMotionArgs downMotionArgs =
2595 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2596 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2597 mDispatcher->notifyMotion(&downMotionArgs);
2598
2599 firstWindow->assertNoEvents();
2600 const MotionEvent* event = secondWindow->consumeMotion();
2601 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2602
2603 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2604 EXPECT_EQ(300, event->getRawX(0));
2605 EXPECT_EQ(880, event->getRawY(0));
2606
2607 // Ensure that the x and y values are in the window's coordinate space.
2608 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2609 // the logical display space. This will be the origin of the window space.
2610 EXPECT_EQ(100, event->getX(0));
2611 EXPECT_EQ(80, event->getY(0));
2612}
2613
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002614using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2615 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002616
2617class TransferTouchFixture : public InputDispatcherTest,
2618 public ::testing::WithParamInterface<TransferFunction> {};
2619
2620TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002622
2623 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002624 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002625 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2626 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002627 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002628 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2629 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002630
2631 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002633
2634 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002635 NotifyMotionArgs downMotionArgs =
2636 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2637 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002638 mDispatcher->notifyMotion(&downMotionArgs);
2639 // Only the first window should get the down event
2640 firstWindow->consumeMotionDown();
2641 secondWindow->assertNoEvents();
2642
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002643 // Transfer touch to the second window
2644 TransferFunction f = GetParam();
2645 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2646 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002647 // The first window gets cancel and the second gets down
2648 firstWindow->consumeMotionCancel();
2649 secondWindow->consumeMotionDown();
2650
2651 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002652 NotifyMotionArgs upMotionArgs =
2653 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2654 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002655 mDispatcher->notifyMotion(&upMotionArgs);
2656 // The first window gets no events and the second gets up
2657 firstWindow->assertNoEvents();
2658 secondWindow->consumeMotionUp();
2659}
2660
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002661/**
2662 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2663 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2664 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2665 * natural to the user.
2666 * In this test, we are sending a pointer to both spy window and first window. We then try to
2667 * transfer touch to the second window. The dispatcher should identify the first window as the
2668 * one that should lose the gesture, and therefore the action should be to move the gesture from
2669 * the first window to the second.
2670 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2671 * the other API, as well.
2672 */
2673TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2674 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2675
2676 // Create a couple of windows + a spy window
2677 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002678 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002679 spyWindow->setTrustedOverlay(true);
2680 spyWindow->setSpy(true);
2681 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002682 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002683 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002684 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002685
2686 // Add the windows to the dispatcher
2687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2688
2689 // Send down to the first window
2690 NotifyMotionArgs downMotionArgs =
2691 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2692 ADISPLAY_ID_DEFAULT);
2693 mDispatcher->notifyMotion(&downMotionArgs);
2694 // Only the first window and spy should get the down event
2695 spyWindow->consumeMotionDown();
2696 firstWindow->consumeMotionDown();
2697
2698 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2699 // if f === 'transferTouch'.
2700 TransferFunction f = GetParam();
2701 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2702 ASSERT_TRUE(success);
2703 // The first window gets cancel and the second gets down
2704 firstWindow->consumeMotionCancel();
2705 secondWindow->consumeMotionDown();
2706
2707 // Send up event to the second window
2708 NotifyMotionArgs upMotionArgs =
2709 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2710 ADISPLAY_ID_DEFAULT);
2711 mDispatcher->notifyMotion(&upMotionArgs);
2712 // The first window gets no events and the second+spy get up
2713 firstWindow->assertNoEvents();
2714 spyWindow->consumeMotionUp();
2715 secondWindow->consumeMotionUp();
2716}
2717
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002718TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002719 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002720
2721 PointF touchPoint = {10, 10};
2722
2723 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002724 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002725 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2726 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002727 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002728 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002729 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2730 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002731 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002732
2733 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002735
2736 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002737 NotifyMotionArgs downMotionArgs =
2738 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2739 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002740 mDispatcher->notifyMotion(&downMotionArgs);
2741 // Only the first window should get the down event
2742 firstWindow->consumeMotionDown();
2743 secondWindow->assertNoEvents();
2744
2745 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002746 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002747 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002748 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002749 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2750 // Only the first window should get the pointer down event
2751 firstWindow->consumeMotionPointerDown(1);
2752 secondWindow->assertNoEvents();
2753
2754 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002755 TransferFunction f = GetParam();
2756 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2757 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002758 // The first window gets cancel and the second gets down and pointer down
2759 firstWindow->consumeMotionCancel();
2760 secondWindow->consumeMotionDown();
2761 secondWindow->consumeMotionPointerDown(1);
2762
2763 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002764 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002765 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002766 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002767 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2768 // The first window gets nothing and the second gets pointer up
2769 firstWindow->assertNoEvents();
2770 secondWindow->consumeMotionPointerUp(1);
2771
2772 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002773 NotifyMotionArgs upMotionArgs =
2774 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2775 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002776 mDispatcher->notifyMotion(&upMotionArgs);
2777 // The first window gets nothing and the second gets up
2778 firstWindow->assertNoEvents();
2779 secondWindow->consumeMotionUp();
2780}
2781
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002782// For the cases of single pointer touch and two pointers non-split touch, the api's
2783// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2784// for the case where there are multiple pointers split across several windows.
2785INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2786 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002787 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2788 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002789 return dispatcher->transferTouch(destChannelToken,
2790 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002791 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002792 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2793 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002794 return dispatcher->transferTouchFocus(from, to,
2795 false /*isDragAndDrop*/);
2796 }));
2797
Svet Ganov5d3bc372020-01-26 23:11:07 -08002798TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002799 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002800
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002801 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002802 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2803 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002804 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002805
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002806 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002807 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2808 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002809 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002810
2811 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002813
2814 PointF pointInFirst = {300, 200};
2815 PointF pointInSecond = {300, 600};
2816
2817 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002818 NotifyMotionArgs firstDownMotionArgs =
2819 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2820 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002821 mDispatcher->notifyMotion(&firstDownMotionArgs);
2822 // Only the first window should get the down event
2823 firstWindow->consumeMotionDown();
2824 secondWindow->assertNoEvents();
2825
2826 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002827 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002828 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002829 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002830 mDispatcher->notifyMotion(&secondDownMotionArgs);
2831 // The first window gets a move and the second a down
2832 firstWindow->consumeMotionMove();
2833 secondWindow->consumeMotionDown();
2834
2835 // Transfer touch focus to the second window
2836 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2837 // The first window gets cancel and the new gets pointer down (it already saw down)
2838 firstWindow->consumeMotionCancel();
2839 secondWindow->consumeMotionPointerDown(1);
2840
2841 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002842 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002843 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002844 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002845 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2846 // The first window gets nothing and the second gets pointer up
2847 firstWindow->assertNoEvents();
2848 secondWindow->consumeMotionPointerUp(1);
2849
2850 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002851 NotifyMotionArgs upMotionArgs =
2852 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2853 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002854 mDispatcher->notifyMotion(&upMotionArgs);
2855 // The first window gets nothing and the second gets up
2856 firstWindow->assertNoEvents();
2857 secondWindow->consumeMotionUp();
2858}
2859
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002860// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2861// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2862// touch is not supported, so the touch should continue on those windows and the transferred-to
2863// window should get nothing.
2864TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2865 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2866
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002867 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002868 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2869 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002870 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002871
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002872 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002873 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2874 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002875 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002876
2877 // Add the windows to the dispatcher
2878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2879
2880 PointF pointInFirst = {300, 200};
2881 PointF pointInSecond = {300, 600};
2882
2883 // Send down to the first window
2884 NotifyMotionArgs firstDownMotionArgs =
2885 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2886 ADISPLAY_ID_DEFAULT, {pointInFirst});
2887 mDispatcher->notifyMotion(&firstDownMotionArgs);
2888 // Only the first window should get the down event
2889 firstWindow->consumeMotionDown();
2890 secondWindow->assertNoEvents();
2891
2892 // Send down to the second window
2893 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002894 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002895 {pointInFirst, pointInSecond});
2896 mDispatcher->notifyMotion(&secondDownMotionArgs);
2897 // The first window gets a move and the second a down
2898 firstWindow->consumeMotionMove();
2899 secondWindow->consumeMotionDown();
2900
2901 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002902 const bool transferred =
2903 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002904 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2905 ASSERT_FALSE(transferred);
2906 firstWindow->assertNoEvents();
2907 secondWindow->assertNoEvents();
2908
2909 // The rest of the dispatch should proceed as normal
2910 // Send pointer up to the second window
2911 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002912 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002913 {pointInFirst, pointInSecond});
2914 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2915 // The first window gets MOVE and the second gets pointer up
2916 firstWindow->consumeMotionMove();
2917 secondWindow->consumeMotionUp();
2918
2919 // Send up event to the first window
2920 NotifyMotionArgs upMotionArgs =
2921 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2922 ADISPLAY_ID_DEFAULT);
2923 mDispatcher->notifyMotion(&upMotionArgs);
2924 // The first window gets nothing and the second gets up
2925 firstWindow->consumeMotionUp();
2926 secondWindow->assertNoEvents();
2927}
2928
Arthur Hungabbb9d82021-09-01 14:52:30 +00002929// This case will create two windows and one mirrored window on the default display and mirror
2930// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2931// the windows info of second display before default display.
2932TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2933 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2934 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002935 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002936 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002937 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002938 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002939 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002940
2941 sp<FakeWindowHandle> mirrorWindowInPrimary =
2942 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2943 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002944
2945 sp<FakeWindowHandle> firstWindowInSecondary =
2946 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2947 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002948
2949 sp<FakeWindowHandle> secondWindowInSecondary =
2950 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2951 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002952
2953 // Update window info, let it find window handle of second display first.
2954 mDispatcher->setInputWindows(
2955 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2956 {ADISPLAY_ID_DEFAULT,
2957 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2958
2959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2961 {50, 50}))
2962 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2963
2964 // Window should receive motion event.
2965 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2966
2967 // Transfer touch focus
2968 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2969 secondWindowInPrimary->getToken()));
2970 // The first window gets cancel.
2971 firstWindowInPrimary->consumeMotionCancel();
2972 secondWindowInPrimary->consumeMotionDown();
2973
2974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2976 ADISPLAY_ID_DEFAULT, {150, 50}))
2977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2978 firstWindowInPrimary->assertNoEvents();
2979 secondWindowInPrimary->consumeMotionMove();
2980
2981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2982 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2983 {150, 50}))
2984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2985 firstWindowInPrimary->assertNoEvents();
2986 secondWindowInPrimary->consumeMotionUp();
2987}
2988
2989// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2990// 'transferTouch' api.
2991TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2992 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2993 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002994 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002995 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002996 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002997 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002998 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002999
3000 sp<FakeWindowHandle> mirrorWindowInPrimary =
3001 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3002 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003003
3004 sp<FakeWindowHandle> firstWindowInSecondary =
3005 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3006 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003007
3008 sp<FakeWindowHandle> secondWindowInSecondary =
3009 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3010 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003011
3012 // Update window info, let it find window handle of second display first.
3013 mDispatcher->setInputWindows(
3014 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3015 {ADISPLAY_ID_DEFAULT,
3016 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3017
3018 // Touch on second display.
3019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3020 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3022
3023 // Window should receive motion event.
3024 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3025
3026 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003027 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003028
3029 // The first window gets cancel.
3030 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3031 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3032
3033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3034 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3035 SECOND_DISPLAY_ID, {150, 50}))
3036 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3037 firstWindowInPrimary->assertNoEvents();
3038 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3039
3040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3041 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3043 firstWindowInPrimary->assertNoEvents();
3044 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3045}
3046
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003047TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003048 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003049 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3050 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003051
Vishnu Nair47074b82020-08-14 11:54:47 -07003052 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003054 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003055
3056 window->consumeFocusEvent(true);
3057
3058 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3059 mDispatcher->notifyKey(&keyArgs);
3060
3061 // Window should receive key down event.
3062 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3063}
3064
3065TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003066 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003067 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3068 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003069
Arthur Hung72d8dc32020-03-28 00:48:39 +00003070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003071
3072 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3073 mDispatcher->notifyKey(&keyArgs);
3074 mDispatcher->waitForIdle();
3075
3076 window->assertNoEvents();
3077}
3078
3079// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3080TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003081 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003082 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3083 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003084
Arthur Hung72d8dc32020-03-28 00:48:39 +00003085 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003086
3087 // Send key
3088 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3089 mDispatcher->notifyKey(&keyArgs);
3090 // Send motion
3091 NotifyMotionArgs motionArgs =
3092 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3093 ADISPLAY_ID_DEFAULT);
3094 mDispatcher->notifyMotion(&motionArgs);
3095
3096 // Window should receive only the motion event
3097 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3098 window->assertNoEvents(); // Key event or focus event will not be received
3099}
3100
arthurhungea3f4fc2020-12-21 23:18:53 +08003101TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3102 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3103
arthurhungea3f4fc2020-12-21 23:18:53 +08003104 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003105 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3106 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003107 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003108
arthurhungea3f4fc2020-12-21 23:18:53 +08003109 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003110 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3111 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003112 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003113
3114 // Add the windows to the dispatcher
3115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3116
3117 PointF pointInFirst = {300, 200};
3118 PointF pointInSecond = {300, 600};
3119
3120 // Send down to the first window
3121 NotifyMotionArgs firstDownMotionArgs =
3122 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3123 ADISPLAY_ID_DEFAULT, {pointInFirst});
3124 mDispatcher->notifyMotion(&firstDownMotionArgs);
3125 // Only the first window should get the down event
3126 firstWindow->consumeMotionDown();
3127 secondWindow->assertNoEvents();
3128
3129 // Send down to the second window
3130 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003131 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003132 {pointInFirst, pointInSecond});
3133 mDispatcher->notifyMotion(&secondDownMotionArgs);
3134 // The first window gets a move and the second a down
3135 firstWindow->consumeMotionMove();
3136 secondWindow->consumeMotionDown();
3137
3138 // Send pointer cancel to the second window
3139 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003140 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003141 {pointInFirst, pointInSecond});
3142 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3143 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3144 // The first window gets move and the second gets cancel.
3145 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3146 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3147
3148 // Send up event.
3149 NotifyMotionArgs upMotionArgs =
3150 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3151 ADISPLAY_ID_DEFAULT);
3152 mDispatcher->notifyMotion(&upMotionArgs);
3153 // The first window gets up and the second gets nothing.
3154 firstWindow->consumeMotionUp();
3155 secondWindow->assertNoEvents();
3156}
3157
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003158TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3159 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3160
3161 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003162 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3164 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3165 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3166 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3167
3168 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3169 window->assertNoEvents();
3170 mDispatcher->waitForIdle();
3171}
3172
chaviwd1c23182019-12-20 18:44:56 -08003173class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003174public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003175 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003176 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003177 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003178 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003179 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003180 }
3181
chaviwd1c23182019-12-20 18:44:56 -08003182 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3183
3184 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3185 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3186 expectedDisplayId, expectedFlags);
3187 }
3188
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003189 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3190
3191 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3192
chaviwd1c23182019-12-20 18:44:56 -08003193 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3194 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3195 expectedDisplayId, expectedFlags);
3196 }
3197
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003198 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3199 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3200 expectedDisplayId, expectedFlags);
3201 }
3202
chaviwd1c23182019-12-20 18:44:56 -08003203 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3204 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3205 expectedDisplayId, expectedFlags);
3206 }
3207
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003208 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3209 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3210 expectedDisplayId, expectedFlags);
3211 }
3212
Arthur Hungfbfa5722021-11-16 02:45:54 +00003213 void consumeMotionPointerDown(int32_t pointerIdx) {
3214 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3215 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3216 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3217 0 /*expectedFlags*/);
3218 }
3219
Evan Rosky84f07f02021-04-16 10:42:42 -07003220 MotionEvent* consumeMotion() {
3221 InputEvent* event = mInputReceiver->consume();
3222 if (!event) {
3223 ADD_FAILURE() << "No event was produced";
3224 return nullptr;
3225 }
3226 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3227 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3228 return nullptr;
3229 }
3230 return static_cast<MotionEvent*>(event);
3231 }
3232
chaviwd1c23182019-12-20 18:44:56 -08003233 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3234
3235private:
3236 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003237};
3238
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003239using InputDispatcherMonitorTest = InputDispatcherTest;
3240
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003241/**
3242 * Two entities that receive touch: A window, and a global monitor.
3243 * The touch goes to the window, and then the window disappears.
3244 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3245 * for the monitor, as well.
3246 * 1. foregroundWindow
3247 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3248 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003249TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003250 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3251 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003252 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003253
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003254 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003255
3256 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3258 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3259 {100, 200}))
3260 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3261
3262 // Both the foreground window and the global monitor should receive the touch down
3263 window->consumeMotionDown();
3264 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3265
3266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3267 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3268 ADISPLAY_ID_DEFAULT, {110, 200}))
3269 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3270
3271 window->consumeMotionMove();
3272 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3273
3274 // Now the foreground window goes away
3275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3276 window->consumeMotionCancel();
3277 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3278
3279 // If more events come in, there will be no more foreground window to send them to. This will
3280 // cause a cancel for the monitor, as well.
3281 ASSERT_EQ(InputEventInjectionResult::FAILED,
3282 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3283 ADISPLAY_ID_DEFAULT, {120, 200}))
3284 << "Injection should fail because the window was removed";
3285 window->assertNoEvents();
3286 // Global monitor now gets the cancel
3287 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3288}
3289
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003290TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003292 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3293 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003295
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003296 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003297
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003299 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003301 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003302 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003303}
3304
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003305TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3306 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003307
Chris Yea209fde2020-07-22 13:54:51 -07003308 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003309 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3310 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003312
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003314 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003315 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003316 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003317 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003318
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003319 // Pilfer pointers from the monitor.
3320 // This should not do anything and the window should continue to receive events.
3321 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003322
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003324 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3325 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003327
3328 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3329 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003330}
3331
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003332TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003333 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003334 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3335 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3337 window->setWindowOffset(20, 40);
3338 window->setWindowTransform(0, 1, -1, 0);
3339
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003340 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003341
3342 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3343 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3344 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3345 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3346 MotionEvent* event = monitor.consumeMotion();
3347 // Even though window has transform, gesture monitor must not.
3348 ASSERT_EQ(ui::Transform(), event->getTransform());
3349}
3350
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003351TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003352 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003353 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003354
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003355 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003356 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003357 << "Injection should fail if there is a monitor, but no touchable window";
3358 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003359}
3360
chaviw81e2bb92019-12-18 15:03:51 -08003361TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003362 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003363 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3364 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003365
Arthur Hung72d8dc32020-03-28 00:48:39 +00003366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003367
3368 NotifyMotionArgs motionArgs =
3369 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3370 ADISPLAY_ID_DEFAULT);
3371
3372 mDispatcher->notifyMotion(&motionArgs);
3373 // Window should receive motion down event.
3374 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3375
3376 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003377 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003378 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3379 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3380 motionArgs.pointerCoords[0].getX() - 10);
3381
3382 mDispatcher->notifyMotion(&motionArgs);
3383 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3384 0 /*expectedFlags*/);
3385}
3386
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003387/**
3388 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3389 * the device default right away. In the test scenario, we check both the default value,
3390 * and the action of enabling / disabling.
3391 */
3392TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003393 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003394 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3395 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003396 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003397
3398 // Set focused application.
3399 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003400 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003401
3402 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003404 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003405 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3406
3407 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003408 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003410 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3411
3412 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003413 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003414 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003415 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003416 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003418 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003419 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3420
3421 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003422 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003424 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3425
3426 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003427 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003428 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003429 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003430 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003432 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003433 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3434
3435 window->assertNoEvents();
3436}
3437
Gang Wange9087892020-01-07 12:17:14 -05003438TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003439 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003440 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3441 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003442
3443 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003444 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003445
Arthur Hung72d8dc32020-03-28 00:48:39 +00003446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003447 setFocusedWindow(window);
3448
Gang Wange9087892020-01-07 12:17:14 -05003449 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3450
3451 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3452 mDispatcher->notifyKey(&keyArgs);
3453
3454 InputEvent* event = window->consume();
3455 ASSERT_NE(event, nullptr);
3456
3457 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3458 ASSERT_NE(verified, nullptr);
3459 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3460
3461 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3462 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3463 ASSERT_EQ(keyArgs.source, verified->source);
3464 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3465
3466 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3467
3468 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003469 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003470 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003471 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3472 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3473 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3474 ASSERT_EQ(0, verifiedKey.repeatCount);
3475}
3476
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003477TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003478 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003479 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3480 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003481
3482 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3483
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003484 ui::Transform transform;
3485 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3486
3487 gui::DisplayInfo displayInfo;
3488 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3489 displayInfo.transform = transform;
3490
3491 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003492
3493 NotifyMotionArgs motionArgs =
3494 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3495 ADISPLAY_ID_DEFAULT);
3496 mDispatcher->notifyMotion(&motionArgs);
3497
3498 InputEvent* event = window->consume();
3499 ASSERT_NE(event, nullptr);
3500
3501 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3502 ASSERT_NE(verified, nullptr);
3503 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3504
3505 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3506 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3507 EXPECT_EQ(motionArgs.source, verified->source);
3508 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3509
3510 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3511
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003512 const vec2 rawXY =
3513 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3514 motionArgs.pointerCoords[0].getXYValue());
3515 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3516 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003517 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003518 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003519 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003520 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3521 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3522}
3523
chaviw09c8d2d2020-08-24 15:48:26 -07003524/**
3525 * Ensure that separate calls to sign the same data are generating the same key.
3526 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3527 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3528 * tests.
3529 */
3530TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3531 KeyEvent event = getTestKeyEvent();
3532 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3533
3534 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3535 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3536 ASSERT_EQ(hmac1, hmac2);
3537}
3538
3539/**
3540 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3541 */
3542TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3543 KeyEvent event = getTestKeyEvent();
3544 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3545 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3546
3547 verifiedEvent.deviceId += 1;
3548 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3549
3550 verifiedEvent.source += 1;
3551 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3552
3553 verifiedEvent.eventTimeNanos += 1;
3554 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3555
3556 verifiedEvent.displayId += 1;
3557 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3558
3559 verifiedEvent.action += 1;
3560 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3561
3562 verifiedEvent.downTimeNanos += 1;
3563 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3564
3565 verifiedEvent.flags += 1;
3566 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3567
3568 verifiedEvent.keyCode += 1;
3569 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3570
3571 verifiedEvent.scanCode += 1;
3572 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3573
3574 verifiedEvent.metaState += 1;
3575 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3576
3577 verifiedEvent.repeatCount += 1;
3578 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3579}
3580
Vishnu Nair958da932020-08-21 17:12:37 -07003581TEST_F(InputDispatcherTest, SetFocusedWindow) {
3582 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3583 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003584 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003585 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003586 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003587 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3588
3589 // Top window is also focusable but is not granted focus.
3590 windowTop->setFocusable(true);
3591 windowSecond->setFocusable(true);
3592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3593 setFocusedWindow(windowSecond);
3594
3595 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3597 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003598
3599 // Focused window should receive event.
3600 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3601 windowTop->assertNoEvents();
3602}
3603
3604TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3606 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003607 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003608 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3609
3610 window->setFocusable(true);
3611 // Release channel for window is no longer valid.
3612 window->releaseChannel();
3613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3614 setFocusedWindow(window);
3615
3616 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003617 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3618 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003619
3620 // window channel is invalid, so it should not receive any input event.
3621 window->assertNoEvents();
3622}
3623
3624TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3625 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3626 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003627 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003628 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003629 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3630
Vishnu Nair958da932020-08-21 17:12:37 -07003631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3632 setFocusedWindow(window);
3633
3634 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003635 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3636 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003637
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003638 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003639 window->assertNoEvents();
3640}
3641
3642TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3644 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003645 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003646 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003647 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003648 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3649
3650 windowTop->setFocusable(true);
3651 windowSecond->setFocusable(true);
3652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3653 setFocusedWindow(windowTop);
3654 windowTop->consumeFocusEvent(true);
3655
3656 setFocusedWindow(windowSecond, windowTop);
3657 windowSecond->consumeFocusEvent(true);
3658 windowTop->consumeFocusEvent(false);
3659
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3661 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003662
3663 // Focused window should receive event.
3664 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3665}
3666
3667TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3669 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003670 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003671 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003672 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003673 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3674
3675 windowTop->setFocusable(true);
3676 windowSecond->setFocusable(true);
3677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3678 setFocusedWindow(windowSecond, windowTop);
3679
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003680 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3681 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003682
3683 // Event should be dropped.
3684 windowTop->assertNoEvents();
3685 windowSecond->assertNoEvents();
3686}
3687
3688TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3690 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003691 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003692 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003693 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3694 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003695 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3696
3697 window->setFocusable(true);
3698 previousFocusedWindow->setFocusable(true);
3699 window->setVisible(false);
3700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3701 setFocusedWindow(previousFocusedWindow);
3702 previousFocusedWindow->consumeFocusEvent(true);
3703
3704 // Requesting focus on invisible window takes focus from currently focused window.
3705 setFocusedWindow(window);
3706 previousFocusedWindow->consumeFocusEvent(false);
3707
3708 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003710 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003711 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003712
3713 // Window does not get focus event or key down.
3714 window->assertNoEvents();
3715
3716 // Window becomes visible.
3717 window->setVisible(true);
3718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3719
3720 // Window receives focus event.
3721 window->consumeFocusEvent(true);
3722 // Focused window receives key down.
3723 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3724}
3725
Vishnu Nair599f1412021-06-21 10:39:58 -07003726TEST_F(InputDispatcherTest, DisplayRemoved) {
3727 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3728 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003729 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003730 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3731
3732 // window is granted focus.
3733 window->setFocusable(true);
3734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3735 setFocusedWindow(window);
3736 window->consumeFocusEvent(true);
3737
3738 // When a display is removed window loses focus.
3739 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3740 window->consumeFocusEvent(false);
3741}
3742
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003743/**
3744 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3745 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3746 * of the 'slipperyEnterWindow'.
3747 *
3748 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3749 * a way so that the touched location is no longer covered by the top window.
3750 *
3751 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3752 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3753 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3754 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3755 * with ACTION_DOWN).
3756 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3757 * window moved itself away from the touched location and had Flag::SLIPPERY.
3758 *
3759 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3760 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3761 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3762 *
3763 * In this test, we ensure that the event received by the bottom window has
3764 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3765 */
3766TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003767 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3768 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003769
3770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3771 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3772
3773 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003774 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003775 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003776 // Make sure this one overlaps the bottom window
3777 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3778 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3779 // one. Windows with the same owner are not considered to be occluding each other.
3780 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3781
3782 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003783 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003784 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3785
3786 mDispatcher->setInputWindows(
3787 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3788
3789 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3790 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3791 ADISPLAY_ID_DEFAULT, {{50, 50}});
3792 mDispatcher->notifyMotion(&args);
3793 slipperyExitWindow->consumeMotionDown();
3794 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3795 mDispatcher->setInputWindows(
3796 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3797
3798 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3799 ADISPLAY_ID_DEFAULT, {{51, 51}});
3800 mDispatcher->notifyMotion(&args);
3801
3802 slipperyExitWindow->consumeMotionCancel();
3803
3804 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3805 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3806}
3807
Garfield Tan1c7bc862020-01-28 13:24:04 -08003808class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3809protected:
3810 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3811 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3812
Chris Yea209fde2020-07-22 13:54:51 -07003813 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003814 sp<FakeWindowHandle> mWindow;
3815
3816 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003817 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003818 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003819 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003820 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3821 ASSERT_EQ(OK, mDispatcher->start());
3822
3823 setUpWindow();
3824 }
3825
3826 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003827 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003828 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003829
Vishnu Nair47074b82020-08-14 11:54:47 -07003830 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003832 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003833 mWindow->consumeFocusEvent(true);
3834 }
3835
Chris Ye2ad95392020-09-01 13:44:44 -07003836 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003837 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003838 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003839 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3840 mDispatcher->notifyKey(&keyArgs);
3841
3842 // Window should receive key down event.
3843 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3844 }
3845
3846 void expectKeyRepeatOnce(int32_t repeatCount) {
3847 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3848 InputEvent* repeatEvent = mWindow->consume();
3849 ASSERT_NE(nullptr, repeatEvent);
3850
3851 uint32_t eventType = repeatEvent->getType();
3852 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3853
3854 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3855 uint32_t eventAction = repeatKeyEvent->getAction();
3856 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3857 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3858 }
3859
Chris Ye2ad95392020-09-01 13:44:44 -07003860 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003861 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003862 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003863 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3864 mDispatcher->notifyKey(&keyArgs);
3865
3866 // Window should receive key down event.
3867 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3868 0 /*expectedFlags*/);
3869 }
3870};
3871
3872TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003873 sendAndConsumeKeyDown(1 /* deviceId */);
3874 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3875 expectKeyRepeatOnce(repeatCount);
3876 }
3877}
3878
3879TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3880 sendAndConsumeKeyDown(1 /* deviceId */);
3881 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3882 expectKeyRepeatOnce(repeatCount);
3883 }
3884 sendAndConsumeKeyDown(2 /* deviceId */);
3885 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003886 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3887 expectKeyRepeatOnce(repeatCount);
3888 }
3889}
3890
3891TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003892 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003893 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003894 sendAndConsumeKeyUp(1 /* deviceId */);
3895 mWindow->assertNoEvents();
3896}
3897
3898TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3899 sendAndConsumeKeyDown(1 /* deviceId */);
3900 expectKeyRepeatOnce(1 /*repeatCount*/);
3901 sendAndConsumeKeyDown(2 /* deviceId */);
3902 expectKeyRepeatOnce(1 /*repeatCount*/);
3903 // Stale key up from device 1.
3904 sendAndConsumeKeyUp(1 /* deviceId */);
3905 // Device 2 is still down, keep repeating
3906 expectKeyRepeatOnce(2 /*repeatCount*/);
3907 expectKeyRepeatOnce(3 /*repeatCount*/);
3908 // Device 2 key up
3909 sendAndConsumeKeyUp(2 /* deviceId */);
3910 mWindow->assertNoEvents();
3911}
3912
3913TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3914 sendAndConsumeKeyDown(1 /* deviceId */);
3915 expectKeyRepeatOnce(1 /*repeatCount*/);
3916 sendAndConsumeKeyDown(2 /* deviceId */);
3917 expectKeyRepeatOnce(1 /*repeatCount*/);
3918 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3919 sendAndConsumeKeyUp(2 /* deviceId */);
3920 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003921 mWindow->assertNoEvents();
3922}
3923
liushenxiang42232912021-05-21 20:24:09 +08003924TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3925 sendAndConsumeKeyDown(DEVICE_ID);
3926 expectKeyRepeatOnce(1 /*repeatCount*/);
3927 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3928 mDispatcher->notifyDeviceReset(&args);
3929 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3930 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3931 mWindow->assertNoEvents();
3932}
3933
Garfield Tan1c7bc862020-01-28 13:24:04 -08003934TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003935 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003936 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3937 InputEvent* repeatEvent = mWindow->consume();
3938 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3939 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3940 IdGenerator::getSource(repeatEvent->getId()));
3941 }
3942}
3943
3944TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003945 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003946
3947 std::unordered_set<int32_t> idSet;
3948 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3949 InputEvent* repeatEvent = mWindow->consume();
3950 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3951 int32_t id = repeatEvent->getId();
3952 EXPECT_EQ(idSet.end(), idSet.find(id));
3953 idSet.insert(id);
3954 }
3955}
3956
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003957/* Test InputDispatcher for MultiDisplay */
3958class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3959public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003960 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003961 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003962
Chris Yea209fde2020-07-22 13:54:51 -07003963 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003964 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003965 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003966
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003967 // Set focus window for primary display, but focused display would be second one.
3968 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003969 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003971 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003972 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003973
Chris Yea209fde2020-07-22 13:54:51 -07003974 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003975 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003976 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003977 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003978 // Set focus display to second one.
3979 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3980 // Set focus window for second display.
3981 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003982 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003983 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003984 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003985 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003986 }
3987
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003988 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003989 InputDispatcherTest::TearDown();
3990
Chris Yea209fde2020-07-22 13:54:51 -07003991 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003992 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003993 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003994 windowInSecondary.clear();
3995 }
3996
3997protected:
Chris Yea209fde2020-07-22 13:54:51 -07003998 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003999 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004000 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004001 sp<FakeWindowHandle> windowInSecondary;
4002};
4003
4004TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4005 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4007 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4008 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004009 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004010 windowInSecondary->assertNoEvents();
4011
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004012 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4014 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004016 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004017 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004018}
4019
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004020TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004021 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4023 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004024 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004025 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004026 windowInSecondary->assertNoEvents();
4027
4028 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004030 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004031 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004032 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004033
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004034 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004035 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004036
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004037 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004038 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4039 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004040
4041 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004042 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004043 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004044 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004045 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004046 windowInSecondary->assertNoEvents();
4047}
4048
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004049// Test per-display input monitors for motion event.
4050TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004051 FakeMonitorReceiver monitorInPrimary =
4052 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4053 FakeMonitorReceiver monitorInSecondary =
4054 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004055
4056 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4058 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4059 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004060 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004061 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004062 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004063 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004064
4065 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4067 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4068 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004069 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004070 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004071 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004072 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004073
4074 // Test inject a non-pointer motion event.
4075 // If specific a display, it will dispatch to the focused window of particular display,
4076 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4078 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004080 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004081 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004082 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004083 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004084}
4085
4086// Test per-display input monitors for key event.
4087TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004088 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004089 FakeMonitorReceiver monitorInPrimary =
4090 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4091 FakeMonitorReceiver monitorInSecondary =
4092 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004093
4094 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4096 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004097 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004098 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004099 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004100 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004101}
4102
Vishnu Nair958da932020-08-21 17:12:37 -07004103TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4104 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004105 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004106 secondWindowInPrimary->setFocusable(true);
4107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4108 setFocusedWindow(secondWindowInPrimary);
4109 windowInPrimary->consumeFocusEvent(false);
4110 secondWindowInPrimary->consumeFocusEvent(true);
4111
4112 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4114 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004115 windowInPrimary->assertNoEvents();
4116 windowInSecondary->assertNoEvents();
4117 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4118}
4119
Arthur Hungdfd528e2021-12-08 13:23:04 +00004120TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4121 FakeMonitorReceiver monitorInPrimary =
4122 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4123 FakeMonitorReceiver monitorInSecondary =
4124 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4125
4126 // Test touch down on primary display.
4127 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4128 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4129 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4130 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4131 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4132
4133 // Test touch down on second display.
4134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4135 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4136 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4137 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4138 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4139
4140 // Trigger cancel touch.
4141 mDispatcher->cancelCurrentTouch();
4142 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4143 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4144 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4145 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4146
4147 // Test inject a move motion event, no window/monitor should receive the event.
4148 ASSERT_EQ(InputEventInjectionResult::FAILED,
4149 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4150 ADISPLAY_ID_DEFAULT, {110, 200}))
4151 << "Inject motion event should return InputEventInjectionResult::FAILED";
4152 windowInPrimary->assertNoEvents();
4153 monitorInPrimary.assertNoEvents();
4154
4155 ASSERT_EQ(InputEventInjectionResult::FAILED,
4156 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4157 SECOND_DISPLAY_ID, {110, 200}))
4158 << "Inject motion event should return InputEventInjectionResult::FAILED";
4159 windowInSecondary->assertNoEvents();
4160 monitorInSecondary.assertNoEvents();
4161}
4162
Jackal Guof9696682018-10-05 12:23:23 +08004163class InputFilterTest : public InputDispatcherTest {
4164protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004165 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4166 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004167 NotifyMotionArgs motionArgs;
4168
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004169 motionArgs =
4170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004171 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004172 motionArgs =
4173 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004174 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004175 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004176 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004177 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4178 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004179 } else {
4180 mFakePolicy->assertFilterInputEventWasNotCalled();
4181 }
4182 }
4183
4184 void testNotifyKey(bool expectToBeFiltered) {
4185 NotifyKeyArgs keyArgs;
4186
4187 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4188 mDispatcher->notifyKey(&keyArgs);
4189 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4190 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004191 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004192
4193 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004194 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004195 } else {
4196 mFakePolicy->assertFilterInputEventWasNotCalled();
4197 }
4198 }
4199};
4200
4201// Test InputFilter for MotionEvent
4202TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4203 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4204 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4205 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4206
4207 // Enable InputFilter
4208 mDispatcher->setInputFilterEnabled(true);
4209 // Test touch on both primary and second display, and check if both events are filtered.
4210 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4211 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4212
4213 // Disable InputFilter
4214 mDispatcher->setInputFilterEnabled(false);
4215 // Test touch on both primary and second display, and check if both events aren't filtered.
4216 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4217 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4218}
4219
4220// Test InputFilter for KeyEvent
4221TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4222 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4223 testNotifyKey(/*expectToBeFiltered*/ false);
4224
4225 // Enable InputFilter
4226 mDispatcher->setInputFilterEnabled(true);
4227 // Send a key event, and check if it is filtered.
4228 testNotifyKey(/*expectToBeFiltered*/ true);
4229
4230 // Disable InputFilter
4231 mDispatcher->setInputFilterEnabled(false);
4232 // Send a key event, and check if it isn't filtered.
4233 testNotifyKey(/*expectToBeFiltered*/ false);
4234}
4235
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004236// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4237// logical display coordinate space.
4238TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4239 ui::Transform firstDisplayTransform;
4240 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4241 ui::Transform secondDisplayTransform;
4242 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4243
4244 std::vector<gui::DisplayInfo> displayInfos(2);
4245 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4246 displayInfos[0].transform = firstDisplayTransform;
4247 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4248 displayInfos[1].transform = secondDisplayTransform;
4249
4250 mDispatcher->onWindowInfosChanged({}, displayInfos);
4251
4252 // Enable InputFilter
4253 mDispatcher->setInputFilterEnabled(true);
4254
4255 // Ensure the correct transforms are used for the displays.
4256 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4257 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4258}
4259
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004260class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4261protected:
4262 virtual void SetUp() override {
4263 InputDispatcherTest::SetUp();
4264
4265 /**
4266 * We don't need to enable input filter to test the injected event policy, but we enabled it
4267 * here to make the tests more realistic, since this policy only matters when inputfilter is
4268 * on.
4269 */
4270 mDispatcher->setInputFilterEnabled(true);
4271
4272 std::shared_ptr<InputApplicationHandle> application =
4273 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004274 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4275 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004276
4277 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4278 mWindow->setFocusable(true);
4279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4280 setFocusedWindow(mWindow);
4281 mWindow->consumeFocusEvent(true);
4282 }
4283
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004284 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4285 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286 KeyEvent event;
4287
4288 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4289 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4290 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4291 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4292 const int32_t additionalPolicyFlags =
4293 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004295 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004296 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4297 policyFlags | additionalPolicyFlags));
4298
4299 InputEvent* received = mWindow->consume();
4300 ASSERT_NE(nullptr, received);
4301 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004302 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4303 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4304 ASSERT_EQ(flags, keyEvent.getFlags());
4305 }
4306
4307 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4308 int32_t flags) {
4309 MotionEvent event;
4310 PointerProperties pointerProperties[1];
4311 PointerCoords pointerCoords[1];
4312 pointerProperties[0].clear();
4313 pointerProperties[0].id = 0;
4314 pointerCoords[0].clear();
4315 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4316 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4317
4318 ui::Transform identityTransform;
4319 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4320 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4321 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4322 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4323 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004324 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004325 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004326 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4327
4328 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004330 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004331 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4332 policyFlags | additionalPolicyFlags));
4333
4334 InputEvent* received = mWindow->consume();
4335 ASSERT_NE(nullptr, received);
4336 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4337 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4338 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4339 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004340 }
4341
4342private:
4343 sp<FakeWindowHandle> mWindow;
4344};
4345
4346TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004347 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4348 // filter. Without it, the event will no different from a regularly injected event, and the
4349 // injected device id will be overwritten.
4350 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4351 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004352}
4353
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004354TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004355 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004356 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4357 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4358}
4359
4360TEST_F(InputFilterInjectionPolicyTest,
4361 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4362 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4363 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4364 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004365}
4366
4367TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4368 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004369 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004370}
4371
chaviwfd6d3512019-03-25 13:23:49 -07004372class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004373 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004374 InputDispatcherTest::SetUp();
4375
Chris Yea209fde2020-07-22 13:54:51 -07004376 std::shared_ptr<FakeApplicationHandle> application =
4377 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004378 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004379 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004380 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004381
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004382 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004383 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004384 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004385
4386 // Set focused application.
4387 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004388 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004389
4390 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004392 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004393 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004394 }
4395
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004396 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004397 InputDispatcherTest::TearDown();
4398
4399 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004400 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004401 }
4402
4403protected:
4404 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004405 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004406 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004407};
4408
4409// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4410// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4411// the onPointerDownOutsideFocus callback.
4412TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004414 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4415 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004417 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004418
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004419 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004420 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4421}
4422
4423// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4424// DOWN on the window that doesn't have focus. Ensure no window received the
4425// onPointerDownOutsideFocus callback.
4426TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004430 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004431
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004432 ASSERT_TRUE(mDispatcher->waitForIdle());
4433 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004434}
4435
4436// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4437// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4438TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4440 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004442 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004443
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004444 ASSERT_TRUE(mDispatcher->waitForIdle());
4445 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004446}
4447
4448// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4449// DOWN on the window that already has focus. Ensure no window received the
4450// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004451TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004453 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004454 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004455 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004456 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004457
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004458 ASSERT_TRUE(mDispatcher->waitForIdle());
4459 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004460}
4461
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004462// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4463// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4464TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4465 const MotionEvent event =
4466 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4467 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4468 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4469 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4470 .build();
4471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4472 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4473 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4474
4475 ASSERT_TRUE(mDispatcher->waitForIdle());
4476 mFakePolicy->assertOnPointerDownWasNotCalled();
4477 // Ensure that the unfocused window did not receive any FOCUS events.
4478 mUnfocusedWindow->assertNoEvents();
4479}
4480
chaviwaf87b3e2019-10-01 16:59:28 -07004481// These tests ensures we can send touch events to a single client when there are multiple input
4482// windows that point to the same client token.
4483class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4484 virtual void SetUp() override {
4485 InputDispatcherTest::SetUp();
4486
Chris Yea209fde2020-07-22 13:54:51 -07004487 std::shared_ptr<FakeApplicationHandle> application =
4488 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004489 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4490 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004491 mWindow1->setFrame(Rect(0, 0, 100, 100));
4492
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004493 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4494 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004495 mWindow2->setFrame(Rect(100, 100, 200, 200));
4496
Arthur Hung72d8dc32020-03-28 00:48:39 +00004497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004498 }
4499
4500protected:
4501 sp<FakeWindowHandle> mWindow1;
4502 sp<FakeWindowHandle> mWindow2;
4503
4504 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004505 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004506 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4507 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004508 }
4509
4510 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4511 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004512 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004513 InputEvent* event = window->consume();
4514
4515 ASSERT_NE(nullptr, event) << name.c_str()
4516 << ": consumer should have returned non-NULL event.";
4517
4518 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4519 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4520 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4521
4522 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004523 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004524
4525 for (size_t i = 0; i < points.size(); i++) {
4526 float expectedX = points[i].x;
4527 float expectedY = points[i].y;
4528
4529 EXPECT_EQ(expectedX, motionEvent.getX(i))
4530 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4531 << ", got " << motionEvent.getX(i);
4532 EXPECT_EQ(expectedY, motionEvent.getY(i))
4533 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4534 << ", got " << motionEvent.getY(i);
4535 }
4536 }
chaviw9eaa22c2020-07-01 16:21:27 -07004537
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004538 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004539 std::vector<PointF> expectedPoints) {
4540 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4541 ADISPLAY_ID_DEFAULT, touchedPoints);
4542 mDispatcher->notifyMotion(&motionArgs);
4543
4544 // Always consume from window1 since it's the window that has the InputReceiver
4545 consumeMotionEvent(mWindow1, action, expectedPoints);
4546 }
chaviwaf87b3e2019-10-01 16:59:28 -07004547};
4548
4549TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4550 // Touch Window 1
4551 PointF touchedPoint = {10, 10};
4552 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004553 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004554
4555 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004556 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004557
4558 // Touch Window 2
4559 touchedPoint = {150, 150};
4560 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004561 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004562}
4563
chaviw9eaa22c2020-07-01 16:21:27 -07004564TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4565 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004566 mWindow2->setWindowScale(0.5f, 0.5f);
4567
4568 // Touch Window 1
4569 PointF touchedPoint = {10, 10};
4570 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004571 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004572 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004573 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004574
4575 // Touch Window 2
4576 touchedPoint = {150, 150};
4577 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004578 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4579 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004580
chaviw9eaa22c2020-07-01 16:21:27 -07004581 // Update the transform so rotation is set
4582 mWindow2->setWindowTransform(0, -1, 1, 0);
4583 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4584 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004585}
4586
chaviw9eaa22c2020-07-01 16:21:27 -07004587TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004588 mWindow2->setWindowScale(0.5f, 0.5f);
4589
4590 // Touch Window 1
4591 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4592 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004593 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004594
4595 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004596 touchedPoints.push_back(PointF{150, 150});
4597 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004598 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004599
chaviw9eaa22c2020-07-01 16:21:27 -07004600 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004601 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004602 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004603
chaviw9eaa22c2020-07-01 16:21:27 -07004604 // Update the transform so rotation is set for Window 2
4605 mWindow2->setWindowTransform(0, -1, 1, 0);
4606 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004607 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004608}
4609
chaviw9eaa22c2020-07-01 16:21:27 -07004610TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004611 mWindow2->setWindowScale(0.5f, 0.5f);
4612
4613 // Touch Window 1
4614 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4615 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004616 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004617
4618 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004619 touchedPoints.push_back(PointF{150, 150});
4620 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004621
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004622 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004623
4624 // Move both windows
4625 touchedPoints = {{20, 20}, {175, 175}};
4626 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4627 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4628
chaviw9eaa22c2020-07-01 16:21:27 -07004629 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004630
chaviw9eaa22c2020-07-01 16:21:27 -07004631 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004632 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004633 expectedPoints.pop_back();
4634
4635 // Touch Window 2
4636 mWindow2->setWindowTransform(0, -1, 1, 0);
4637 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004638 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004639
4640 // Move both windows
4641 touchedPoints = {{20, 20}, {175, 175}};
4642 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4643 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4644
4645 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004646}
4647
4648TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4649 mWindow1->setWindowScale(0.5f, 0.5f);
4650
4651 // Touch Window 1
4652 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4653 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004654 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004655
4656 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004657 touchedPoints.push_back(PointF{150, 150});
4658 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004659
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004660 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004661
4662 // Move both windows
4663 touchedPoints = {{20, 20}, {175, 175}};
4664 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4665 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4666
chaviw9eaa22c2020-07-01 16:21:27 -07004667 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004668}
4669
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004670class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4671 virtual void SetUp() override {
4672 InputDispatcherTest::SetUp();
4673
Chris Yea209fde2020-07-22 13:54:51 -07004674 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004675 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004676 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4677 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004678 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004679 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004680 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004681
4682 // Set focused application.
4683 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4684
4685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004686 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004687 mWindow->consumeFocusEvent(true);
4688 }
4689
4690 virtual void TearDown() override {
4691 InputDispatcherTest::TearDown();
4692 mWindow.clear();
4693 }
4694
4695protected:
Chris Yea209fde2020-07-22 13:54:51 -07004696 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004697 sp<FakeWindowHandle> mWindow;
4698 static constexpr PointF WINDOW_LOCATION = {20, 20};
4699
4700 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4703 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004705 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4706 WINDOW_LOCATION));
4707 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004708
4709 sp<FakeWindowHandle> addSpyWindow() {
4710 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004711 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004712 spy->setTrustedOverlay(true);
4713 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004714 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004715 spy->setDispatchingTimeout(30ms);
4716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4717 return spy;
4718 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004719};
4720
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721// Send a tap and respond, which should not cause an ANR.
4722TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4723 tapOnWindow();
4724 mWindow->consumeMotionDown();
4725 mWindow->consumeMotionUp();
4726 ASSERT_TRUE(mDispatcher->waitForIdle());
4727 mFakePolicy->assertNotifyAnrWasNotCalled();
4728}
4729
4730// Send a regular key and respond, which should not cause an ANR.
4731TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4734 ASSERT_TRUE(mDispatcher->waitForIdle());
4735 mFakePolicy->assertNotifyAnrWasNotCalled();
4736}
4737
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004738TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4739 mWindow->setFocusable(false);
4740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4741 mWindow->consumeFocusEvent(false);
4742
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004743 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004744 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004745 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4746 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004748 // Key will not go to window because we have no focused window.
4749 // The 'no focused window' ANR timer should start instead.
4750
4751 // Now, the focused application goes away.
4752 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4753 // The key should get dropped and there should be no ANR.
4754
4755 ASSERT_TRUE(mDispatcher->waitForIdle());
4756 mFakePolicy->assertNotifyAnrWasNotCalled();
4757}
4758
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004759// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4761// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004762TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004764 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4765 WINDOW_LOCATION));
4766
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004767 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4768 ASSERT_TRUE(sequenceNum);
4769 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004770 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004771
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772 mWindow->finishEvent(*sequenceNum);
4773 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4774 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004775 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004776 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004777}
4778
4779// Send a key to the app and have the app not respond right away.
4780TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4781 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004782 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004783 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4784 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004785 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004786 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004787 ASSERT_TRUE(mDispatcher->waitForIdle());
4788}
4789
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790// We have a focused application, but no focused window
4791TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004792 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4794 mWindow->consumeFocusEvent(false);
4795
4796 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4799 WINDOW_LOCATION));
4800 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4801 mDispatcher->waitForIdle();
4802 mFakePolicy->assertNotifyAnrWasNotCalled();
4803
4804 // Once a focused event arrives, we get an ANR for this application
4805 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4806 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004807 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004809 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07004812 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 ASSERT_TRUE(mDispatcher->waitForIdle());
4814}
4815
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004816/**
4817 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4818 * there will not be an ANR.
4819 */
4820TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4821 mWindow->setFocusable(false);
4822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4823 mWindow->consumeFocusEvent(false);
4824
4825 KeyEvent event;
4826 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4827 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4828
4829 // Define a valid key down event that is stale (too old).
4830 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4831 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4832 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4833
4834 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4835
4836 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004837 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004838 InputEventInjectionSync::WAIT_FOR_RESULT,
4839 INJECT_EVENT_TIMEOUT, policyFlags);
4840 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4841 << "Injection should fail because the event is stale";
4842
4843 ASSERT_TRUE(mDispatcher->waitForIdle());
4844 mFakePolicy->assertNotifyAnrWasNotCalled();
4845 mWindow->assertNoEvents();
4846}
4847
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004849// Make sure that we don't notify policy twice about the same ANR.
4850TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004851 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4853 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004854
4855 // Once a focused event arrives, we get an ANR for this application
4856 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4857 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004858 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004860 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004861 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07004862 const std::chrono::duration appTimeout =
4863 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4864 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865
Vishnu Naire4df8752022-09-08 09:17:55 -07004866 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004867 // ANR should not be raised again. It is up to policy to do that if it desires.
4868 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004869
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004870 // If we now get a focused window, the ANR should stop, but the policy handles that via
4871 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 ASSERT_TRUE(mDispatcher->waitForIdle());
4873}
4874
4875// We have a focused application, but no focused window
4876TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004877 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4879 mWindow->consumeFocusEvent(false);
4880
4881 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004882 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004884 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4885 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886
Vishnu Naire4df8752022-09-08 09:17:55 -07004887 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4888 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889
4890 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004891 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004892 ASSERT_TRUE(mDispatcher->waitForIdle());
4893 mWindow->assertNoEvents();
4894}
4895
4896/**
4897 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4898 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4899 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4900 * the ANR mechanism should still work.
4901 *
4902 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4903 * DOWN event, while not responding on the second one.
4904 */
4905TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4906 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4907 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4908 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4909 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4910 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004911 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004912
4913 // Now send ACTION_UP, with identical timestamp
4914 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4915 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4916 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4917 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004918 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919
4920 // We have now sent down and up. Let's consume first event and then ANR on the second.
4921 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4922 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004923 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924}
4925
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004926// A spy window can receive an ANR
4927TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4928 sp<FakeWindowHandle> spy = addSpyWindow();
4929
4930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4931 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4932 WINDOW_LOCATION));
4933 mWindow->consumeMotionDown();
4934
4935 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4936 ASSERT_TRUE(sequenceNum);
4937 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004938 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004939
4940 spy->finishEvent(*sequenceNum);
4941 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4942 0 /*flags*/);
4943 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004944 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004945}
4946
4947// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004949TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4950 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4953 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956
4957 // Stuck on the ACTION_UP
4958 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004959 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004961 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004963 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4964 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965
4966 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4967 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004968 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004969 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004970 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971}
4972
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004973// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004975TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4976 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004977
4978 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004979 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4980 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981
4982 mWindow->consumeMotionDown();
4983 // Stuck on the ACTION_UP
4984 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004985 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004987 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004989 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4990 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991
4992 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4993 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004994 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004995 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004996 spy->assertNoEvents();
4997}
4998
4999TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5000 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5001
5002 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5003
5004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5006 WINDOW_LOCATION));
5007
5008 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5009 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5010 ASSERT_TRUE(consumeSeq);
5011
Prabir Pradhanedd96402022-02-15 01:46:16 -08005012 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005013
5014 monitor.finishEvent(*consumeSeq);
5015 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5016
5017 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005018 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005019}
5020
5021// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5022// process events, you don't get an anr. When the window later becomes unresponsive again, you
5023// get an ANR again.
5024// 1. tap -> block on ACTION_UP -> receive ANR
5025// 2. consume all pending events (= queue becomes healthy again)
5026// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5027TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5028 tapOnWindow();
5029
5030 mWindow->consumeMotionDown();
5031 // Block on ACTION_UP
5032 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005033 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005034 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5035 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005036 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037 mWindow->assertNoEvents();
5038
5039 tapOnWindow();
5040 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005041 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042 mWindow->consumeMotionUp();
5043
5044 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005045 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005046 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047 mWindow->assertNoEvents();
5048}
5049
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005050// If a connection remains unresponsive for a while, make sure policy is only notified once about
5051// it.
5052TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5055 WINDOW_LOCATION));
5056
5057 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005058 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005059 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005060 // 'notifyConnectionUnresponsive' should only be called once per connection
5061 mFakePolicy->assertNotifyAnrWasNotCalled();
5062 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005063 mWindow->consumeMotionDown();
5064 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5065 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5066 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005067 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005068 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005069 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005070}
5071
5072/**
5073 * If a window is processing a motion event, and then a key event comes in, the key event should
5074 * not to to the focused window until the motion is processed.
5075 *
5076 * Warning!!!
5077 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5078 * and the injection timeout that we specify when injecting the key.
5079 * We must have the injection timeout (10ms) be smaller than
5080 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5081 *
5082 * If that value changes, this test should also change.
5083 */
5084TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5085 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5087
5088 tapOnWindow();
5089 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5090 ASSERT_TRUE(downSequenceNum);
5091 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5092 ASSERT_TRUE(upSequenceNum);
5093 // Don't finish the events yet, and send a key
5094 // Injection will "succeed" because we will eventually give up and send the key to the focused
5095 // window even if motions are still being processed. But because the injection timeout is short,
5096 // we will receive INJECTION_TIMED_OUT as the result.
5097
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005098 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005100 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5101 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102 // Key will not be sent to the window, yet, because the window is still processing events
5103 // and the key remains pending, waiting for the touch events to be processed
5104 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5105 ASSERT_FALSE(keySequenceNum);
5106
5107 std::this_thread::sleep_for(500ms);
5108 // if we wait long enough though, dispatcher will give up, and still send the key
5109 // to the focused window, even though we have not yet finished the motion event
5110 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5111 mWindow->finishEvent(*downSequenceNum);
5112 mWindow->finishEvent(*upSequenceNum);
5113}
5114
5115/**
5116 * If a window is processing a motion event, and then a key event comes in, the key event should
5117 * not go to the focused window until the motion is processed.
5118 * If then a new motion comes in, then the pending key event should be going to the currently
5119 * focused window right away.
5120 */
5121TEST_F(InputDispatcherSingleWindowAnr,
5122 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5123 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5125
5126 tapOnWindow();
5127 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5128 ASSERT_TRUE(downSequenceNum);
5129 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5130 ASSERT_TRUE(upSequenceNum);
5131 // Don't finish the events yet, and send a key
5132 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005134 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005135 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136 // At this point, key is still pending, and should not be sent to the application yet.
5137 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5138 ASSERT_FALSE(keySequenceNum);
5139
5140 // Now tap down again. It should cause the pending key to go to the focused window right away.
5141 tapOnWindow();
5142 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5143 // the other events yet. We can finish events in any order.
5144 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5145 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5146 mWindow->consumeMotionDown();
5147 mWindow->consumeMotionUp();
5148 mWindow->assertNoEvents();
5149}
5150
5151class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5152 virtual void SetUp() override {
5153 InputDispatcherTest::SetUp();
5154
Chris Yea209fde2020-07-22 13:54:51 -07005155 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005156 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005157 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5158 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005159 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005160 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005161 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005162
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005163 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5164 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005165 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005166 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005167
5168 // Set focused application.
5169 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005170 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005171
5172 // Expect one focus window exist in display.
5173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005174 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005175 mFocusedWindow->consumeFocusEvent(true);
5176 }
5177
5178 virtual void TearDown() override {
5179 InputDispatcherTest::TearDown();
5180
5181 mUnfocusedWindow.clear();
5182 mFocusedWindow.clear();
5183 }
5184
5185protected:
Chris Yea209fde2020-07-22 13:54:51 -07005186 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005187 sp<FakeWindowHandle> mUnfocusedWindow;
5188 sp<FakeWindowHandle> mFocusedWindow;
5189 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5190 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5191 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5192
5193 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5194
5195 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5196
5197private:
5198 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005200 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5201 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005203 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5204 location));
5205 }
5206};
5207
5208// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5209// should be ANR'd first.
5210TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5213 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005214 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215 mFocusedWindow->consumeMotionDown();
5216 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5217 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5218 // We consumed all events, so no ANR
5219 ASSERT_TRUE(mDispatcher->waitForIdle());
5220 mFakePolicy->assertNotifyAnrWasNotCalled();
5221
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5224 FOCUSED_WINDOW_LOCATION));
5225 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5226 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227
5228 const std::chrono::duration timeout =
5229 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005230 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005231 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5232 // sequence to make it consistent
5233 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005235 mFocusedWindow->consumeMotionDown();
5236 // This cancel is generated because the connection was unresponsive
5237 mFocusedWindow->consumeMotionCancel();
5238 mFocusedWindow->assertNoEvents();
5239 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005240 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005241 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5242 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005243 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244}
5245
5246// If we have 2 windows with identical timeouts that are both unresponsive,
5247// it doesn't matter which order they should have ANR.
5248// But we should receive ANR for both.
5249TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5250 // Set the timeout for unfocused window to match the focused window
5251 mUnfocusedWindow->setDispatchingTimeout(10ms);
5252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5253
5254 tapOnFocusedWindow();
5255 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005256 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5257 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5258 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005259
5260 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005261 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5262 mFocusedWindow->getToken() == anrConnectionToken2);
5263 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5264 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005265
5266 ASSERT_TRUE(mDispatcher->waitForIdle());
5267 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005268
5269 mFocusedWindow->consumeMotionDown();
5270 mFocusedWindow->consumeMotionUp();
5271 mUnfocusedWindow->consumeMotionOutside();
5272
Prabir Pradhanedd96402022-02-15 01:46:16 -08005273 sp<IBinder> responsiveToken1, responsiveToken2;
5274 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5275 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005276
5277 // Both applications should be marked as responsive, in any order
5278 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5279 mFocusedWindow->getToken() == responsiveToken2);
5280 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5281 mUnfocusedWindow->getToken() == responsiveToken2);
5282 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005283}
5284
5285// If a window is already not responding, the second tap on the same window should be ignored.
5286// We should also log an error to account for the dropped event (not tested here).
5287// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5288TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5289 tapOnFocusedWindow();
5290 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5291 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5292 // Receive the events, but don't respond
5293 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5294 ASSERT_TRUE(downEventSequenceNum);
5295 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5296 ASSERT_TRUE(upEventSequenceNum);
5297 const std::chrono::duration timeout =
5298 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005299 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005300
5301 // Tap once again
5302 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005303 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005304 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5305 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005306 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005307 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5308 FOCUSED_WINDOW_LOCATION));
5309 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5310 // valid touch target
5311 mUnfocusedWindow->assertNoEvents();
5312
5313 // Consume the first tap
5314 mFocusedWindow->finishEvent(*downEventSequenceNum);
5315 mFocusedWindow->finishEvent(*upEventSequenceNum);
5316 ASSERT_TRUE(mDispatcher->waitForIdle());
5317 // The second tap did not go to the focused window
5318 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005319 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005320 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5321 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005322 mFakePolicy->assertNotifyAnrWasNotCalled();
5323}
5324
5325// If you tap outside of all windows, there will not be ANR
5326TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005327 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005328 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5329 LOCATION_OUTSIDE_ALL_WINDOWS));
5330 ASSERT_TRUE(mDispatcher->waitForIdle());
5331 mFakePolicy->assertNotifyAnrWasNotCalled();
5332}
5333
5334// Since the focused window is paused, tapping on it should not produce any events
5335TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5336 mFocusedWindow->setPaused(true);
5337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5338
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005339 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005340 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5341 FOCUSED_WINDOW_LOCATION));
5342
5343 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5344 ASSERT_TRUE(mDispatcher->waitForIdle());
5345 // Should not ANR because the window is paused, and touches shouldn't go to it
5346 mFakePolicy->assertNotifyAnrWasNotCalled();
5347
5348 mFocusedWindow->assertNoEvents();
5349 mUnfocusedWindow->assertNoEvents();
5350}
5351
5352/**
5353 * If a window is processing a motion event, and then a key event comes in, the key event should
5354 * not to to the focused window until the motion is processed.
5355 * If a different window becomes focused at this time, the key should go to that window instead.
5356 *
5357 * Warning!!!
5358 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5359 * and the injection timeout that we specify when injecting the key.
5360 * We must have the injection timeout (10ms) be smaller than
5361 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5362 *
5363 * If that value changes, this test should also change.
5364 */
5365TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5366 // Set a long ANR timeout to prevent it from triggering
5367 mFocusedWindow->setDispatchingTimeout(2s);
5368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5369
5370 tapOnUnfocusedWindow();
5371 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5372 ASSERT_TRUE(downSequenceNum);
5373 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5374 ASSERT_TRUE(upSequenceNum);
5375 // Don't finish the events yet, and send a key
5376 // Injection will succeed because we will eventually give up and send the key to the focused
5377 // window even if motions are still being processed.
5378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005379 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005380 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005381 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005383 // Key will not be sent to the window, yet, because the window is still processing events
5384 // and the key remains pending, waiting for the touch events to be processed
5385 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5386 ASSERT_FALSE(keySequenceNum);
5387
5388 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005389 mFocusedWindow->setFocusable(false);
5390 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005392 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005393
5394 // Focus events should precede the key events
5395 mUnfocusedWindow->consumeFocusEvent(true);
5396 mFocusedWindow->consumeFocusEvent(false);
5397
5398 // Finish the tap events, which should unblock dispatcher
5399 mUnfocusedWindow->finishEvent(*downSequenceNum);
5400 mUnfocusedWindow->finishEvent(*upSequenceNum);
5401
5402 // Now that all queues are cleared and no backlog in the connections, the key event
5403 // can finally go to the newly focused "mUnfocusedWindow".
5404 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5405 mFocusedWindow->assertNoEvents();
5406 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005407 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005408}
5409
5410// When the touch stream is split across 2 windows, and one of them does not respond,
5411// then ANR should be raised and the touch should be canceled for the unresponsive window.
5412// The other window should not be affected by that.
5413TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5414 // Touch Window 1
5415 NotifyMotionArgs motionArgs =
5416 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5417 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5418 mDispatcher->notifyMotion(&motionArgs);
5419 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5420 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5421
5422 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005423 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5424 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005425 mDispatcher->notifyMotion(&motionArgs);
5426
5427 const std::chrono::duration timeout =
5428 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005429 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005430
5431 mUnfocusedWindow->consumeMotionDown();
5432 mFocusedWindow->consumeMotionDown();
5433 // Focused window may or may not receive ACTION_MOVE
5434 // But it should definitely receive ACTION_CANCEL due to the ANR
5435 InputEvent* event;
5436 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5437 ASSERT_TRUE(moveOrCancelSequenceNum);
5438 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5439 ASSERT_NE(nullptr, event);
5440 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5441 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5442 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5443 mFocusedWindow->consumeMotionCancel();
5444 } else {
5445 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5446 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005447 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005448 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5449 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005450
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005451 mUnfocusedWindow->assertNoEvents();
5452 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005453 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454}
5455
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005456/**
5457 * If we have no focused window, and a key comes in, we start the ANR timer.
5458 * The focused application should add a focused window before the timer runs out to prevent ANR.
5459 *
5460 * If the user touches another application during this time, the key should be dropped.
5461 * Next, if a new focused window comes in, without toggling the focused application,
5462 * then no ANR should occur.
5463 *
5464 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5465 * but in some cases the policy may not update the focused application.
5466 */
5467TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5468 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5469 std::make_shared<FakeApplicationHandle>();
5470 focusedApplication->setDispatchingTimeout(60ms);
5471 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5472 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5473 mFocusedWindow->setFocusable(false);
5474
5475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5476 mFocusedWindow->consumeFocusEvent(false);
5477
5478 // Send a key. The ANR timer should start because there is no focused window.
5479 // 'focusedApplication' will get blamed if this timer completes.
5480 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005481 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005482 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005483 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5484 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005486
5487 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5488 // then the injected touches won't cause the focused event to get dropped.
5489 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5490 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5491 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5492 // For this test, it means that the key would get delivered to the window once it becomes
5493 // focused.
5494 std::this_thread::sleep_for(10ms);
5495
5496 // Touch unfocused window. This should force the pending key to get dropped.
5497 NotifyMotionArgs motionArgs =
5498 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5499 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5500 mDispatcher->notifyMotion(&motionArgs);
5501
5502 // We do not consume the motion right away, because that would require dispatcher to first
5503 // process (== drop) the key event, and by that time, ANR will be raised.
5504 // Set the focused window first.
5505 mFocusedWindow->setFocusable(true);
5506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5507 setFocusedWindow(mFocusedWindow);
5508 mFocusedWindow->consumeFocusEvent(true);
5509 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5510 // to another application. This could be a bug / behaviour in the policy.
5511
5512 mUnfocusedWindow->consumeMotionDown();
5513
5514 ASSERT_TRUE(mDispatcher->waitForIdle());
5515 // Should not ANR because we actually have a focused window. It was just added too slowly.
5516 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5517}
5518
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005519// These tests ensure we cannot send touch events to a window that's positioned behind a window
5520// that has feature NO_INPUT_CHANNEL.
5521// Layout:
5522// Top (closest to user)
5523// mNoInputWindow (above all windows)
5524// mBottomWindow
5525// Bottom (furthest from user)
5526class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5527 virtual void SetUp() override {
5528 InputDispatcherTest::SetUp();
5529
5530 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005531 mNoInputWindow =
5532 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5533 "Window without input channel", ADISPLAY_ID_DEFAULT,
5534 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005535 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005536 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5537 // It's perfectly valid for this window to not have an associated input channel
5538
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005539 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5540 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005541 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5542
5543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5544 }
5545
5546protected:
5547 std::shared_ptr<FakeApplicationHandle> mApplication;
5548 sp<FakeWindowHandle> mNoInputWindow;
5549 sp<FakeWindowHandle> mBottomWindow;
5550};
5551
5552TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5553 PointF touchedPoint = {10, 10};
5554
5555 NotifyMotionArgs motionArgs =
5556 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5557 ADISPLAY_ID_DEFAULT, {touchedPoint});
5558 mDispatcher->notifyMotion(&motionArgs);
5559
5560 mNoInputWindow->assertNoEvents();
5561 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5562 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5563 // and therefore should prevent mBottomWindow from receiving touches
5564 mBottomWindow->assertNoEvents();
5565}
5566
5567/**
5568 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5569 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5570 */
5571TEST_F(InputDispatcherMultiWindowOcclusionTests,
5572 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005573 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5574 "Window with input channel and NO_INPUT_CHANNEL",
5575 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005576
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005577 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005578 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5580
5581 PointF touchedPoint = {10, 10};
5582
5583 NotifyMotionArgs motionArgs =
5584 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5585 ADISPLAY_ID_DEFAULT, {touchedPoint});
5586 mDispatcher->notifyMotion(&motionArgs);
5587
5588 mNoInputWindow->assertNoEvents();
5589 mBottomWindow->assertNoEvents();
5590}
5591
Vishnu Nair958da932020-08-21 17:12:37 -07005592class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5593protected:
5594 std::shared_ptr<FakeApplicationHandle> mApp;
5595 sp<FakeWindowHandle> mWindow;
5596 sp<FakeWindowHandle> mMirror;
5597
5598 virtual void SetUp() override {
5599 InputDispatcherTest::SetUp();
5600 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005601 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5602 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5603 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005604 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5605 mWindow->setFocusable(true);
5606 mMirror->setFocusable(true);
5607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5608 }
5609};
5610
5611TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5612 // Request focus on a mirrored window
5613 setFocusedWindow(mMirror);
5614
5615 // window gets focused
5616 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5618 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005619 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5620}
5621
5622// A focused & mirrored window remains focused only if the window and its mirror are both
5623// focusable.
5624TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5625 setFocusedWindow(mMirror);
5626
5627 // window gets focused
5628 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5630 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005631 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5633 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005634 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5635
5636 mMirror->setFocusable(false);
5637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5638
5639 // window loses focus since one of the windows associated with the token in not focusable
5640 mWindow->consumeFocusEvent(false);
5641
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005642 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5643 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005644 mWindow->assertNoEvents();
5645}
5646
5647// A focused & mirrored window remains focused until the window and its mirror both become
5648// invisible.
5649TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
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);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5658 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005659 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5660
5661 mMirror->setVisible(false);
5662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5663
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5665 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005666 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5668 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005669 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5670
5671 mWindow->setVisible(false);
5672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5673
5674 // window loses focus only after all windows associated with the token become invisible.
5675 mWindow->consumeFocusEvent(false);
5676
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005677 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5678 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005679 mWindow->assertNoEvents();
5680}
5681
5682// A focused & mirrored window remains focused until both windows are removed.
5683TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5684 setFocusedWindow(mMirror);
5685
5686 // window gets focused
5687 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5689 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005690 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5692 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005693 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5694
5695 // single window is removed but the window token remains focused
5696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5697
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5699 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005700 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5702 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005703 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5704
5705 // Both windows are removed
5706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5707 mWindow->consumeFocusEvent(false);
5708
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005709 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5710 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005711 mWindow->assertNoEvents();
5712}
5713
5714// Focus request can be pending until one window becomes visible.
5715TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5716 // Request focus on an invisible mirror.
5717 mWindow->setVisible(false);
5718 mMirror->setVisible(false);
5719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5720 setFocusedWindow(mMirror);
5721
5722 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005724 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005725 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005726
5727 mMirror->setVisible(true);
5728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5729
5730 // window gets focused
5731 mWindow->consumeFocusEvent(true);
5732 // window gets the pending key event
5733 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5734}
Prabir Pradhan99987712020-11-10 18:43:05 -08005735
5736class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5737protected:
5738 std::shared_ptr<FakeApplicationHandle> mApp;
5739 sp<FakeWindowHandle> mWindow;
5740 sp<FakeWindowHandle> mSecondWindow;
5741
5742 void SetUp() override {
5743 InputDispatcherTest::SetUp();
5744 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005745 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005746 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005747 mSecondWindow =
5748 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005749 mSecondWindow->setFocusable(true);
5750
5751 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5753
5754 setFocusedWindow(mWindow);
5755 mWindow->consumeFocusEvent(true);
5756 }
5757
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005758 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5759 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005760 mDispatcher->notifyPointerCaptureChanged(&args);
5761 }
5762
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005763 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5764 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005765 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005766 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5767 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005768 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005769 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005770 }
5771};
5772
5773TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5774 // Ensure that capture cannot be obtained for unfocused windows.
5775 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5776 mFakePolicy->assertSetPointerCaptureNotCalled();
5777 mSecondWindow->assertNoEvents();
5778
5779 // Ensure that capture can be enabled from the focus window.
5780 requestAndVerifyPointerCapture(mWindow, true);
5781
5782 // Ensure that capture cannot be disabled from a window that does not have capture.
5783 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5784 mFakePolicy->assertSetPointerCaptureNotCalled();
5785
5786 // Ensure that capture can be disabled from the window with capture.
5787 requestAndVerifyPointerCapture(mWindow, false);
5788}
5789
5790TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005791 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005792
5793 setFocusedWindow(mSecondWindow);
5794
5795 // Ensure that the capture disabled event was sent first.
5796 mWindow->consumeCaptureEvent(false);
5797 mWindow->consumeFocusEvent(false);
5798 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005799 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005800
5801 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005802 notifyPointerCaptureChanged({});
5803 notifyPointerCaptureChanged(request);
5804 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005805 mWindow->assertNoEvents();
5806 mSecondWindow->assertNoEvents();
5807 mFakePolicy->assertSetPointerCaptureNotCalled();
5808}
5809
5810TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005811 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005812
5813 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005814 notifyPointerCaptureChanged({});
5815 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005816
5817 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005818 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005819 mWindow->consumeCaptureEvent(false);
5820 mWindow->assertNoEvents();
5821}
5822
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005823TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5824 requestAndVerifyPointerCapture(mWindow, true);
5825
5826 // The first window loses focus.
5827 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005828 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005829 mWindow->consumeCaptureEvent(false);
5830
5831 // Request Pointer Capture from the second window before the notification from InputReader
5832 // arrives.
5833 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005834 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005835
5836 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005837 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005838
5839 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005840 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005841
5842 mSecondWindow->consumeFocusEvent(true);
5843 mSecondWindow->consumeCaptureEvent(true);
5844}
5845
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005846TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5847 // App repeatedly enables and disables capture.
5848 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5849 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5850 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5851 mFakePolicy->assertSetPointerCaptureCalled(false);
5852 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5853 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5854
5855 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5856 // first request is now stale, this should do nothing.
5857 notifyPointerCaptureChanged(firstRequest);
5858 mWindow->assertNoEvents();
5859
5860 // InputReader notifies that the second request was enabled.
5861 notifyPointerCaptureChanged(secondRequest);
5862 mWindow->consumeCaptureEvent(true);
5863}
5864
Prabir Pradhan7092e262022-05-03 16:51:09 +00005865TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5866 requestAndVerifyPointerCapture(mWindow, true);
5867
5868 // App toggles pointer capture off and on.
5869 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5870 mFakePolicy->assertSetPointerCaptureCalled(false);
5871
5872 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5873 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5874
5875 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5876 // preceding "disable" request.
5877 notifyPointerCaptureChanged(enableRequest);
5878
5879 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5880 // any notifications.
5881 mWindow->assertNoEvents();
5882}
5883
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005884class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5885protected:
5886 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005887
5888 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5889 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5890
5891 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5892 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5893
5894 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5895 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5896 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5897 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5898 MAXIMUM_OBSCURING_OPACITY);
5899
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005900 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005901 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005902 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005903
5904 sp<FakeWindowHandle> mTouchWindow;
5905
5906 virtual void SetUp() override {
5907 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005908 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005909 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5910 }
5911
5912 virtual void TearDown() override {
5913 InputDispatcherTest::TearDown();
5914 mTouchWindow.clear();
5915 }
5916
chaviw3277faf2021-05-19 16:45:23 -05005917 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5918 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005919 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005920 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005921 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005922 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005923 return window;
5924 }
5925
5926 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5927 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5928 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005929 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005930 // Generate an arbitrary PID based on the UID
5931 window->setOwnerInfo(1777 + (uid % 10000), uid);
5932 return window;
5933 }
5934
5935 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5936 NotifyMotionArgs args =
5937 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5938 ADISPLAY_ID_DEFAULT, points);
5939 mDispatcher->notifyMotion(&args);
5940 }
5941};
5942
5943TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005944 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005945 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005947
5948 touch();
5949
5950 mTouchWindow->assertNoEvents();
5951}
5952
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005953TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005954 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5955 const sp<FakeWindowHandle>& w =
5956 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5958
5959 touch();
5960
5961 mTouchWindow->assertNoEvents();
5962}
5963
5964TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005965 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5966 const sp<FakeWindowHandle>& w =
5967 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5969
5970 touch();
5971
5972 w->assertNoEvents();
5973}
5974
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005975TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005976 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5977 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005978
5979 touch();
5980
5981 mTouchWindow->consumeAnyMotionDown();
5982}
5983
5984TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005985 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005986 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005987 w->setFrame(Rect(0, 0, 50, 50));
5988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005989
5990 touch({PointF{100, 100}});
5991
5992 mTouchWindow->consumeAnyMotionDown();
5993}
5994
5995TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005996 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005997 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5999
6000 touch();
6001
6002 mTouchWindow->consumeAnyMotionDown();
6003}
6004
6005TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6006 const sp<FakeWindowHandle>& w =
6007 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006009
6010 touch();
6011
6012 mTouchWindow->consumeAnyMotionDown();
6013}
6014
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006015TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6016 const sp<FakeWindowHandle>& w =
6017 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6019
6020 touch();
6021
6022 w->assertNoEvents();
6023}
6024
6025/**
6026 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6027 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6028 * window, the occluding window will still receive ACTION_OUTSIDE event.
6029 */
6030TEST_F(InputDispatcherUntrustedTouchesTest,
6031 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6032 const sp<FakeWindowHandle>& w =
6033 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006034 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6036
6037 touch();
6038
6039 w->consumeMotionOutside();
6040}
6041
6042TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6043 const sp<FakeWindowHandle>& w =
6044 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006045 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6047
6048 touch();
6049
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006050 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006051}
6052
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006053TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006054 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006055 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6056 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6058
6059 touch();
6060
6061 mTouchWindow->consumeAnyMotionDown();
6062}
6063
6064TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6065 const sp<FakeWindowHandle>& w =
6066 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6067 MAXIMUM_OBSCURING_OPACITY);
6068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006069
6070 touch();
6071
6072 mTouchWindow->consumeAnyMotionDown();
6073}
6074
6075TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006076 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006077 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6078 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6080
6081 touch();
6082
6083 mTouchWindow->assertNoEvents();
6084}
6085
6086TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6087 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6088 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006089 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6090 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006091 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006092 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6093 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6095
6096 touch();
6097
6098 mTouchWindow->assertNoEvents();
6099}
6100
6101TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6102 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6103 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006104 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6105 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006106 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006107 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6108 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6110
6111 touch();
6112
6113 mTouchWindow->consumeAnyMotionDown();
6114}
6115
6116TEST_F(InputDispatcherUntrustedTouchesTest,
6117 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6118 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006119 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6120 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006121 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006122 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6123 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6125
6126 touch();
6127
6128 mTouchWindow->consumeAnyMotionDown();
6129}
6130
6131TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6132 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006133 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6134 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006135 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006136 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6137 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006139
6140 touch();
6141
6142 mTouchWindow->assertNoEvents();
6143}
6144
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006145TEST_F(InputDispatcherUntrustedTouchesTest,
6146 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6147 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006148 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6149 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006150 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006151 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6152 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6154
6155 touch();
6156
6157 mTouchWindow->assertNoEvents();
6158}
6159
6160TEST_F(InputDispatcherUntrustedTouchesTest,
6161 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6162 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006163 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6164 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006165 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006166 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6167 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6169
6170 touch();
6171
6172 mTouchWindow->consumeAnyMotionDown();
6173}
6174
6175TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6176 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006177 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6178 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6180
6181 touch();
6182
6183 mTouchWindow->consumeAnyMotionDown();
6184}
6185
6186TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6187 const sp<FakeWindowHandle>& w =
6188 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6189 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6190
6191 touch();
6192
6193 mTouchWindow->consumeAnyMotionDown();
6194}
6195
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006196TEST_F(InputDispatcherUntrustedTouchesTest,
6197 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6198 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6199 const sp<FakeWindowHandle>& w =
6200 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6202
6203 touch();
6204
6205 mTouchWindow->assertNoEvents();
6206}
6207
6208TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6209 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6210 const sp<FakeWindowHandle>& w =
6211 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6213
6214 touch();
6215
6216 mTouchWindow->consumeAnyMotionDown();
6217}
6218
6219TEST_F(InputDispatcherUntrustedTouchesTest,
6220 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6221 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6222 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006223 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6224 OPACITY_ABOVE_THRESHOLD);
6225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6226
6227 touch();
6228
6229 mTouchWindow->consumeAnyMotionDown();
6230}
6231
6232TEST_F(InputDispatcherUntrustedTouchesTest,
6233 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6234 const sp<FakeWindowHandle>& w1 =
6235 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6236 OPACITY_BELOW_THRESHOLD);
6237 const sp<FakeWindowHandle>& w2 =
6238 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6239 OPACITY_BELOW_THRESHOLD);
6240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6241
6242 touch();
6243
6244 mTouchWindow->assertNoEvents();
6245}
6246
6247/**
6248 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6249 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6250 * (which alone would result in allowing touches) does not affect the blocking behavior.
6251 */
6252TEST_F(InputDispatcherUntrustedTouchesTest,
6253 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6254 const sp<FakeWindowHandle>& wB =
6255 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6256 OPACITY_BELOW_THRESHOLD);
6257 const sp<FakeWindowHandle>& wC =
6258 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6259 OPACITY_BELOW_THRESHOLD);
6260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6261
6262 touch();
6263
6264 mTouchWindow->assertNoEvents();
6265}
6266
6267/**
6268 * This test is testing that a window from a different UID but with same application token doesn't
6269 * block the touch. Apps can share the application token for close UI collaboration for example.
6270 */
6271TEST_F(InputDispatcherUntrustedTouchesTest,
6272 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6273 const sp<FakeWindowHandle>& w =
6274 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6275 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006276 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6277
6278 touch();
6279
6280 mTouchWindow->consumeAnyMotionDown();
6281}
6282
arthurhungb89ccb02020-12-30 16:19:01 +08006283class InputDispatcherDragTests : public InputDispatcherTest {
6284protected:
6285 std::shared_ptr<FakeApplicationHandle> mApp;
6286 sp<FakeWindowHandle> mWindow;
6287 sp<FakeWindowHandle> mSecondWindow;
6288 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006289 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006290 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6291 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006292
6293 void SetUp() override {
6294 InputDispatcherTest::SetUp();
6295 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006296 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006297 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006298
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006299 mSecondWindow =
6300 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006301 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006302
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006303 mSpyWindow =
6304 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006305 mSpyWindow->setSpy(true);
6306 mSpyWindow->setTrustedOverlay(true);
6307 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6308
arthurhungb89ccb02020-12-30 16:19:01 +08006309 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006311 }
6312
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006313 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6314 switch (fromSource) {
6315 case AINPUT_SOURCE_TOUCHSCREEN:
6316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6317 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6318 ADISPLAY_ID_DEFAULT, {50, 50}))
6319 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6320 break;
6321 case AINPUT_SOURCE_STYLUS:
6322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6323 injectMotionEvent(
6324 mDispatcher,
6325 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6326 AINPUT_SOURCE_STYLUS)
6327 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6328 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6329 .x(50)
6330 .y(50))
6331 .build()));
6332 break;
6333 case AINPUT_SOURCE_MOUSE:
6334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6335 injectMotionEvent(
6336 mDispatcher,
6337 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6338 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6339 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6340 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6341 .x(50)
6342 .y(50))
6343 .build()));
6344 break;
6345 default:
6346 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6347 }
arthurhungb89ccb02020-12-30 16:19:01 +08006348
6349 // Window should receive motion event.
6350 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006351 // Spy window should also receive motion event
6352 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006353 }
6354
6355 // Start performing drag, we will create a drag window and transfer touch to it.
6356 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6357 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006358 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006359 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006360 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006361 }
arthurhungb89ccb02020-12-30 16:19:01 +08006362
6363 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006364 mDragWindow =
6365 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006366 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006367 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006368 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006369
6370 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006371 bool transferred =
6372 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6373 true /* isDragDrop */);
6374 if (transferred) {
6375 mWindow->consumeMotionCancel();
6376 mDragWindow->consumeMotionDown();
6377 }
6378 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006379 }
6380};
6381
6382TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006383 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006384
6385 // Move on window.
6386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6387 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6388 ADISPLAY_ID_DEFAULT, {50, 50}))
6389 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6390 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6391 mWindow->consumeDragEvent(false, 50, 50);
6392 mSecondWindow->assertNoEvents();
6393
6394 // Move to another window.
6395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6396 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6397 ADISPLAY_ID_DEFAULT, {150, 50}))
6398 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6399 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6400 mWindow->consumeDragEvent(true, 150, 50);
6401 mSecondWindow->consumeDragEvent(false, 50, 50);
6402
6403 // Move back to original window.
6404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6405 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6406 ADISPLAY_ID_DEFAULT, {50, 50}))
6407 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6408 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6409 mWindow->consumeDragEvent(false, 50, 50);
6410 mSecondWindow->consumeDragEvent(true, -50, 50);
6411
6412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6413 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6415 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6416 mWindow->assertNoEvents();
6417 mSecondWindow->assertNoEvents();
6418}
6419
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006420TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006421 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006422
6423 // No cancel event after drag start
6424 mSpyWindow->assertNoEvents();
6425
6426 const MotionEvent secondFingerDownEvent =
6427 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6428 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6429 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6430 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6431 .build();
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6434 InputEventInjectionSync::WAIT_FOR_RESULT))
6435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6436
6437 // Receives cancel for first pointer after next pointer down
6438 mSpyWindow->consumeMotionCancel();
6439 mSpyWindow->consumeMotionDown();
6440
6441 mSpyWindow->assertNoEvents();
6442}
6443
arthurhungf452d0b2021-01-06 00:19:52 +08006444TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006445 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006446
6447 // Move on window.
6448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6449 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6450 ADISPLAY_ID_DEFAULT, {50, 50}))
6451 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6452 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6453 mWindow->consumeDragEvent(false, 50, 50);
6454 mSecondWindow->assertNoEvents();
6455
6456 // Move to another window.
6457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6458 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6459 ADISPLAY_ID_DEFAULT, {150, 50}))
6460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6461 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6462 mWindow->consumeDragEvent(true, 150, 50);
6463 mSecondWindow->consumeDragEvent(false, 50, 50);
6464
6465 // drop to another window.
6466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6467 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6468 {150, 50}))
6469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6470 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6471 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6472 mWindow->assertNoEvents();
6473 mSecondWindow->assertNoEvents();
6474}
6475
arthurhung6d4bed92021-03-17 11:59:33 +08006476TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006477 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006478
6479 // Move on window and keep button pressed.
6480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6481 injectMotionEvent(mDispatcher,
6482 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6483 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6484 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6485 .x(50)
6486 .y(50))
6487 .build()))
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 and release button, expect to drop item.
6494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6495 injectMotionEvent(mDispatcher,
6496 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6497 .buttonState(0)
6498 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6499 .x(150)
6500 .y(50))
6501 .build()))
6502 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6503 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6504 mWindow->assertNoEvents();
6505 mSecondWindow->assertNoEvents();
6506 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6507
6508 // nothing to the window.
6509 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6510 injectMotionEvent(mDispatcher,
6511 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6512 .buttonState(0)
6513 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6514 .x(150)
6515 .y(50))
6516 .build()))
6517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6518 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6519 mWindow->assertNoEvents();
6520 mSecondWindow->assertNoEvents();
6521}
6522
Arthur Hung54745652022-04-20 07:17:41 +00006523TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006524 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006525
6526 // Set second window invisible.
6527 mSecondWindow->setVisible(false);
6528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6529
6530 // Move on window.
6531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6532 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6533 ADISPLAY_ID_DEFAULT, {50, 50}))
6534 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6535 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6536 mWindow->consumeDragEvent(false, 50, 50);
6537 mSecondWindow->assertNoEvents();
6538
6539 // Move to another window.
6540 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6541 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6542 ADISPLAY_ID_DEFAULT, {150, 50}))
6543 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6544 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6545 mWindow->consumeDragEvent(true, 150, 50);
6546 mSecondWindow->assertNoEvents();
6547
6548 // drop to another window.
6549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6550 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6551 {150, 50}))
6552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6553 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6554 mFakePolicy->assertDropTargetEquals(nullptr);
6555 mWindow->assertNoEvents();
6556 mSecondWindow->assertNoEvents();
6557}
6558
Arthur Hung54745652022-04-20 07:17:41 +00006559TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006560 // Ensure window could track pointerIds if it didn't support split touch.
6561 mWindow->setPreventSplitting(true);
6562
Arthur Hung54745652022-04-20 07:17:41 +00006563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6564 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6565 {50, 50}))
6566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6567 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6568
6569 const MotionEvent secondFingerDownEvent =
6570 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6571 .displayId(ADISPLAY_ID_DEFAULT)
6572 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6573 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6574 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6575 .build();
6576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6577 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6578 InputEventInjectionSync::WAIT_FOR_RESULT))
6579 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6580 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6581
6582 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006583 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006584}
6585
6586TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6587 // First down on second window.
6588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6589 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6590 {150, 50}))
6591 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6592
6593 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6594
6595 // Second down on first window.
6596 const MotionEvent secondFingerDownEvent =
6597 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6598 .displayId(ADISPLAY_ID_DEFAULT)
6599 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6600 .pointer(
6601 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6602 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6603 .build();
6604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6605 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6606 InputEventInjectionSync::WAIT_FOR_RESULT))
6607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6608 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6609
6610 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006611 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006612
6613 // Move on window.
6614 const MotionEvent secondFingerMoveEvent =
6615 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6616 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6617 .pointer(
6618 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6619 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6620 .build();
6621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6622 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6623 InputEventInjectionSync::WAIT_FOR_RESULT));
6624 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6625 mWindow->consumeDragEvent(false, 50, 50);
6626 mSecondWindow->consumeMotionMove();
6627
6628 // Release the drag pointer should perform drop.
6629 const MotionEvent secondFingerUpEvent =
6630 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6631 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6632 .pointer(
6633 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6634 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6635 .build();
6636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6637 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6638 InputEventInjectionSync::WAIT_FOR_RESULT));
6639 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6640 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6641 mWindow->assertNoEvents();
6642 mSecondWindow->consumeMotionMove();
6643}
6644
Arthur Hung3915c1f2022-05-31 07:17:17 +00006645TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006646 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006647
6648 // Update window of second display.
6649 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006650 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006651 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6652
6653 // Let second display has a touch state.
6654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6655 injectMotionEvent(mDispatcher,
6656 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6657 AINPUT_SOURCE_TOUCHSCREEN)
6658 .displayId(SECOND_DISPLAY_ID)
6659 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6660 .x(100)
6661 .y(100))
6662 .build()));
6663 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6664 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6665 // Update window again.
6666 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6667
6668 // Move on window.
6669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6670 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6671 ADISPLAY_ID_DEFAULT, {50, 50}))
6672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6673 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6674 mWindow->consumeDragEvent(false, 50, 50);
6675 mSecondWindow->assertNoEvents();
6676
6677 // Move to another window.
6678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6679 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6680 ADISPLAY_ID_DEFAULT, {150, 50}))
6681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6682 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6683 mWindow->consumeDragEvent(true, 150, 50);
6684 mSecondWindow->consumeDragEvent(false, 50, 50);
6685
6686 // drop to another window.
6687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6688 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6689 {150, 50}))
6690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6691 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6692 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6693 mWindow->assertNoEvents();
6694 mSecondWindow->assertNoEvents();
6695}
6696
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006697TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6698 startDrag(true, AINPUT_SOURCE_MOUSE);
6699 // Move on window.
6700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6701 injectMotionEvent(mDispatcher,
6702 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6703 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6704 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6705 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6706 .x(50)
6707 .y(50))
6708 .build()))
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,
6717 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6718 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6719 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6720 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6721 .x(150)
6722 .y(50))
6723 .build()))
6724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6725 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6726 mWindow->consumeDragEvent(true, 150, 50);
6727 mSecondWindow->consumeDragEvent(false, 50, 50);
6728
6729 // drop to another window.
6730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6731 injectMotionEvent(mDispatcher,
6732 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6733 .buttonState(0)
6734 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6735 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6736 .x(150)
6737 .y(50))
6738 .build()))
6739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6740 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6741 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6742 mWindow->assertNoEvents();
6743 mSecondWindow->assertNoEvents();
6744}
6745
Vishnu Nair062a8672021-09-03 16:07:44 -07006746class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6747
6748TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6749 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006750 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6751 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006752 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006753 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6754 window->setFocusable(true);
6755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6756 setFocusedWindow(window);
6757 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6758
6759 // With the flag set, window should not get any input
6760 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6761 mDispatcher->notifyKey(&keyArgs);
6762 window->assertNoEvents();
6763
6764 NotifyMotionArgs motionArgs =
6765 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6766 ADISPLAY_ID_DEFAULT);
6767 mDispatcher->notifyMotion(&motionArgs);
6768 window->assertNoEvents();
6769
6770 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006771 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6773
6774 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6775 mDispatcher->notifyKey(&keyArgs);
6776 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6777
6778 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6779 ADISPLAY_ID_DEFAULT);
6780 mDispatcher->notifyMotion(&motionArgs);
6781 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6782 window->assertNoEvents();
6783}
6784
6785TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6786 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6787 std::make_shared<FakeApplicationHandle>();
6788 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006789 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6790 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006791 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6792 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006793 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006794 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006795 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6796 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006797 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006798 window->setOwnerInfo(222, 222);
6799 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6800 window->setFocusable(true);
6801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6802 setFocusedWindow(window);
6803 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6804
6805 // With the flag set, window should not get any input
6806 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6807 mDispatcher->notifyKey(&keyArgs);
6808 window->assertNoEvents();
6809
6810 NotifyMotionArgs motionArgs =
6811 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6812 ADISPLAY_ID_DEFAULT);
6813 mDispatcher->notifyMotion(&motionArgs);
6814 window->assertNoEvents();
6815
6816 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006817 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6819
6820 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6821 mDispatcher->notifyKey(&keyArgs);
6822 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6823
6824 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6825 ADISPLAY_ID_DEFAULT);
6826 mDispatcher->notifyMotion(&motionArgs);
6827 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6828 window->assertNoEvents();
6829}
6830
6831TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6832 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6833 std::make_shared<FakeApplicationHandle>();
6834 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006835 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6836 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006837 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6838 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006839 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006840 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006841 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6842 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006843 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006844 window->setOwnerInfo(222, 222);
6845 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6846 window->setFocusable(true);
6847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6848 setFocusedWindow(window);
6849 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6850
6851 // With the flag set, window should not get any input
6852 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6853 mDispatcher->notifyKey(&keyArgs);
6854 window->assertNoEvents();
6855
6856 NotifyMotionArgs motionArgs =
6857 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6858 ADISPLAY_ID_DEFAULT);
6859 mDispatcher->notifyMotion(&motionArgs);
6860 window->assertNoEvents();
6861
6862 // When the window is no longer obscured because it went on top, it should get input
6863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6864
6865 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6866 mDispatcher->notifyKey(&keyArgs);
6867 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6868
6869 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6870 ADISPLAY_ID_DEFAULT);
6871 mDispatcher->notifyMotion(&motionArgs);
6872 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6873 window->assertNoEvents();
6874}
6875
Antonio Kantekf16f2832021-09-28 04:39:20 +00006876class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6877protected:
6878 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00006879 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006880 sp<FakeWindowHandle> mWindow;
6881 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00006882 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006883
6884 void SetUp() override {
6885 InputDispatcherTest::SetUp();
6886
6887 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00006888 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006889 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006890 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006891 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006892 mSecondWindow =
6893 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006894 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00006895 mThirdWindow =
6896 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
6897 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
6898 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006899
6900 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00006901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
6902 {SECOND_DISPLAY_ID, {mThirdWindow}}});
6903 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006904 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006905
Antonio Kantek15beb512022-06-13 22:35:41 +00006906 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006907 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00006908 WINDOW_UID, true /* hasPermission */,
6909 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006910 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6911 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006912 mThirdWindow->assertNoEvents();
6913 }
6914
6915 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
6916 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
6917 SECONDARY_WINDOW_UID, true /* hasPermission */,
6918 SECOND_DISPLAY_ID)) {
6919 mWindow->assertNoEvents();
6920 mSecondWindow->assertNoEvents();
6921 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07006922 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006923 }
6924
Antonio Kantek15beb512022-06-13 22:35:41 +00006925 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
6926 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006927 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6928 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006929 mWindow->consumeTouchModeEvent(inTouchMode);
6930 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006931 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00006932 }
6933};
6934
Antonio Kantek26defcf2022-02-08 01:12:27 +00006935TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006936 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00006937 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
6938 windowInfo.ownerPid, windowInfo.ownerUid,
6939 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006940}
6941
Antonio Kantek26defcf2022-02-08 01:12:27 +00006942TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6943 const WindowInfo& windowInfo = *mWindow->getInfo();
6944 int32_t ownerPid = windowInfo.ownerPid;
6945 int32_t ownerUid = windowInfo.ownerUid;
6946 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6947 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006948 ownerUid, false /*hasPermission*/,
6949 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006950 mWindow->assertNoEvents();
6951 mSecondWindow->assertNoEvents();
6952}
6953
6954TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6955 const WindowInfo& windowInfo = *mWindow->getInfo();
6956 int32_t ownerPid = windowInfo.ownerPid;
6957 int32_t ownerUid = windowInfo.ownerUid;
6958 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00006959 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
6960 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006961}
6962
Antonio Kantekf16f2832021-09-28 04:39:20 +00006963TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006964 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006965 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6966 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006967 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006968 mWindow->assertNoEvents();
6969 mSecondWindow->assertNoEvents();
6970}
6971
Antonio Kantek15beb512022-06-13 22:35:41 +00006972TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
6973 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
6974 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6975 windowInfo.ownerPid, windowInfo.ownerUid,
6976 true /*hasPermission*/, SECOND_DISPLAY_ID));
6977 mWindow->assertNoEvents();
6978 mSecondWindow->assertNoEvents();
6979 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
6980}
6981
Antonio Kantek48710e42022-03-24 14:19:30 -07006982TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6983 // Interact with the window first.
6984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6985 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6986 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6987
6988 // Then remove focus.
6989 mWindow->setFocusable(false);
6990 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6991
6992 // Assert that caller can switch touch mode by owning one of the last interacted window.
6993 const WindowInfo& windowInfo = *mWindow->getInfo();
6994 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6995 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006996 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006997}
6998
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006999class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7000public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007001 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007002 std::shared_ptr<FakeApplicationHandle> application =
7003 std::make_shared<FakeApplicationHandle>();
7004 std::string name = "Fake Spy ";
7005 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007006 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7007 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007008 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007009 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007010 return spy;
7011 }
7012
7013 sp<FakeWindowHandle> createForeground() {
7014 std::shared_ptr<FakeApplicationHandle> application =
7015 std::make_shared<FakeApplicationHandle>();
7016 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007017 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7018 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007019 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007020 return window;
7021 }
7022
7023private:
7024 int mSpyCount{0};
7025};
7026
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007027using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007028/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007029 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7030 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007031TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7032 ScopedSilentDeath _silentDeath;
7033
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007034 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007035 spy->setTrustedOverlay(false);
7036 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7037 ".* not a trusted overlay");
7038}
7039
7040/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007041 * Input injection into a display with a spy window but no foreground windows should succeed.
7042 */
7043TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007044 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7046
7047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7048 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7049 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7050 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7051}
7052
7053/**
7054 * Verify the order in which different input windows receive events. The touched foreground window
7055 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7056 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7057 * receive events before ones belows it.
7058 *
7059 * Here, we set up a scenario with four windows in the following Z order from the top:
7060 * spy1, spy2, window, spy3.
7061 * We then inject an event and verify that the foreground "window" receives it first, followed by
7062 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7063 * window.
7064 */
7065TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7066 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007067 auto spy1 = createSpy();
7068 auto spy2 = createSpy();
7069 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7071 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7072 const size_t numChannels = channels.size();
7073
Michael Wright8e9a8562022-02-09 13:44:29 +00007074 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007075 if (!epollFd.ok()) {
7076 FAIL() << "Failed to create epoll fd";
7077 }
7078
7079 for (size_t i = 0; i < numChannels; i++) {
7080 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7081 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7082 FAIL() << "Failed to add fd to epoll";
7083 }
7084 }
7085
7086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7087 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7088 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7089
7090 std::vector<size_t> eventOrder;
7091 std::vector<struct epoll_event> events(numChannels);
7092 for (;;) {
7093 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7094 (100ms).count());
7095 if (nFds < 0) {
7096 FAIL() << "Failed to call epoll_wait";
7097 }
7098 if (nFds == 0) {
7099 break; // epoll_wait timed out
7100 }
7101 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007102 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007103 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007104 channels[i]->consumeMotionDown();
7105 }
7106 }
7107
7108 // Verify the order in which the events were received.
7109 EXPECT_EQ(3u, eventOrder.size());
7110 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7111 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7112 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7113}
7114
7115/**
7116 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7117 */
7118TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7119 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007120 auto spy = createSpy();
7121 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7123
7124 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7125 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7126 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7127 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7128 spy->assertNoEvents();
7129}
7130
7131/**
7132 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7133 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7134 * to the window.
7135 */
7136TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7137 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007138 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007139 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7141
7142 // Inject an event outside the spy window's touchable region.
7143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7144 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7146 window->consumeMotionDown();
7147 spy->assertNoEvents();
7148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7149 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7150 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7151 window->consumeMotionUp();
7152 spy->assertNoEvents();
7153
7154 // Inject an event inside the spy window's touchable region.
7155 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7156 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7157 {5, 10}))
7158 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7159 window->consumeMotionDown();
7160 spy->consumeMotionDown();
7161}
7162
7163/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007164 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007165 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007166 */
7167TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7168 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007169 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007170 auto spy = createSpy();
7171 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007172 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007173 spy->setFrame(Rect{0, 0, 20, 20});
7174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7175
7176 // Inject an event outside the spy window's frame and touchable region.
7177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007178 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7179 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007180 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7181 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007182 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007183}
7184
7185/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007186 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7187 * pointers that are down within its bounds.
7188 */
7189TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7190 auto windowLeft = createForeground();
7191 windowLeft->setFrame({0, 0, 100, 200});
7192 auto windowRight = createForeground();
7193 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007194 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007195 spy->setFrame({0, 0, 200, 200});
7196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7197
7198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7199 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7200 {50, 50}))
7201 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7202 windowLeft->consumeMotionDown();
7203 spy->consumeMotionDown();
7204
7205 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007206 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007207 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7208 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7209 .pointer(
7210 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7211 .build();
7212 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7213 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7214 InputEventInjectionSync::WAIT_FOR_RESULT))
7215 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7216 windowRight->consumeMotionDown();
7217 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7218}
7219
7220/**
7221 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7222 * the spy should receive the second pointer with ACTION_DOWN.
7223 */
7224TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7225 auto window = createForeground();
7226 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007227 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007228 spyRight->setFrame({100, 0, 200, 200});
7229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7230
7231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7232 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7233 {50, 50}))
7234 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7235 window->consumeMotionDown();
7236 spyRight->assertNoEvents();
7237
7238 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007239 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007240 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7241 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7242 .pointer(
7243 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7244 .build();
7245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7246 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7247 InputEventInjectionSync::WAIT_FOR_RESULT))
7248 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7249 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7250 spyRight->consumeMotionDown();
7251}
7252
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007253/**
7254 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7255 * windows should be allowed to control split touch.
7256 */
7257TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007258 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007259 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007260 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007261 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007262
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007263 auto window = createForeground();
7264 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007265
7266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7267
7268 // First finger down, no window touched.
7269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7271 {100, 200}))
7272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7273 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7274 window->assertNoEvents();
7275
7276 // Second finger down on window, the window should receive touch down.
7277 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007278 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007279 .displayId(ADISPLAY_ID_DEFAULT)
7280 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7281 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7282 .x(100)
7283 .y(200))
7284 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7285 .build();
7286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7287 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7288 InputEventInjectionSync::WAIT_FOR_RESULT))
7289 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7290
7291 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7292 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7293}
7294
7295/**
7296 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7297 * do not receive key events.
7298 */
7299TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007300 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007301 spy->setFocusable(false);
7302
7303 auto window = createForeground();
7304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7305 setFocusedWindow(window);
7306 window->consumeFocusEvent(true);
7307
7308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7309 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7310 window->consumeKeyDown(ADISPLAY_ID_NONE);
7311
7312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7313 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7314 window->consumeKeyUp(ADISPLAY_ID_NONE);
7315
7316 spy->assertNoEvents();
7317}
7318
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007319using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7320
7321/**
7322 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7323 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7324 */
7325TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7326 auto window = createForeground();
7327 auto spy1 = createSpy();
7328 auto spy2 = createSpy();
7329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7330
7331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7332 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7333 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7334 window->consumeMotionDown();
7335 spy1->consumeMotionDown();
7336 spy2->consumeMotionDown();
7337
7338 // Pilfer pointers from the second spy window.
7339 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7340 spy2->assertNoEvents();
7341 spy1->consumeMotionCancel();
7342 window->consumeMotionCancel();
7343
7344 // The rest of the gesture should only be sent to the second spy window.
7345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7346 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7347 ADISPLAY_ID_DEFAULT))
7348 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7349 spy2->consumeMotionMove();
7350 spy1->assertNoEvents();
7351 window->assertNoEvents();
7352}
7353
7354/**
7355 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7356 * in the middle of the gesture.
7357 */
7358TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7359 auto window = createForeground();
7360 auto spy = createSpy();
7361 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7362
7363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7364 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7365 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7366 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7367 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7368
7369 window->releaseChannel();
7370
7371 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7372
7373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7374 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7375 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7376 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7377}
7378
7379/**
7380 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7381 * the spy, but not to any other windows.
7382 */
7383TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7384 auto spy = createSpy();
7385 auto window = createForeground();
7386
7387 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7388
7389 // First finger down on the window and the spy.
7390 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7391 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7392 {100, 200}))
7393 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7394 spy->consumeMotionDown();
7395 window->consumeMotionDown();
7396
7397 // Spy window pilfers the pointers.
7398 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7399 window->consumeMotionCancel();
7400
7401 // Second finger down on the window and spy, but the window should not receive the pointer down.
7402 const MotionEvent secondFingerDownEvent =
7403 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7404 .displayId(ADISPLAY_ID_DEFAULT)
7405 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7406 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7407 .x(100)
7408 .y(200))
7409 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7410 .build();
7411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7412 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7413 InputEventInjectionSync::WAIT_FOR_RESULT))
7414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7415
7416 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7417
7418 // Third finger goes down outside all windows, so injection should fail.
7419 const MotionEvent thirdFingerDownEvent =
7420 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7421 .displayId(ADISPLAY_ID_DEFAULT)
7422 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7423 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7424 .x(100)
7425 .y(200))
7426 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7427 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7428 .build();
7429 ASSERT_EQ(InputEventInjectionResult::FAILED,
7430 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7431 InputEventInjectionSync::WAIT_FOR_RESULT))
7432 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7433
7434 spy->assertNoEvents();
7435 window->assertNoEvents();
7436}
7437
7438/**
7439 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7440 */
7441TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7442 auto spy = createSpy();
7443 spy->setFrame(Rect(0, 0, 100, 100));
7444 auto window = createForeground();
7445 window->setFrame(Rect(0, 0, 200, 200));
7446
7447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7448
7449 // First finger down on the window only
7450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7452 {150, 150}))
7453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7454 window->consumeMotionDown();
7455
7456 // Second finger down on the spy and window
7457 const MotionEvent secondFingerDownEvent =
7458 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7459 .displayId(ADISPLAY_ID_DEFAULT)
7460 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7461 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7462 .x(150)
7463 .y(150))
7464 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7465 .build();
7466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7467 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7468 InputEventInjectionSync::WAIT_FOR_RESULT))
7469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7470 spy->consumeMotionDown();
7471 window->consumeMotionPointerDown(1);
7472
7473 // Third finger down on the spy and window
7474 const MotionEvent thirdFingerDownEvent =
7475 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7476 .displayId(ADISPLAY_ID_DEFAULT)
7477 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7478 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7479 .x(150)
7480 .y(150))
7481 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7482 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7483 .build();
7484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7485 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7486 InputEventInjectionSync::WAIT_FOR_RESULT))
7487 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7488 spy->consumeMotionPointerDown(1);
7489 window->consumeMotionPointerDown(2);
7490
7491 // Spy window pilfers the pointers.
7492 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7493 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7494 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7495
7496 spy->assertNoEvents();
7497 window->assertNoEvents();
7498}
7499
7500/**
7501 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7502 * other windows should be canceled. If this results in the cancellation of all pointers for some
7503 * window, then that window should receive ACTION_CANCEL.
7504 */
7505TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7506 auto spy = createSpy();
7507 spy->setFrame(Rect(0, 0, 100, 100));
7508 auto window = createForeground();
7509 window->setFrame(Rect(0, 0, 200, 200));
7510
7511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7512
7513 // First finger down on both spy and window
7514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7515 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7516 {10, 10}))
7517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7518 window->consumeMotionDown();
7519 spy->consumeMotionDown();
7520
7521 // Second finger down on the spy and window
7522 const MotionEvent secondFingerDownEvent =
7523 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7524 .displayId(ADISPLAY_ID_DEFAULT)
7525 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7526 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7527 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7528 .build();
7529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7530 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7531 InputEventInjectionSync::WAIT_FOR_RESULT))
7532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7533 spy->consumeMotionPointerDown(1);
7534 window->consumeMotionPointerDown(1);
7535
7536 // Spy window pilfers the pointers.
7537 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7538 window->consumeMotionCancel();
7539
7540 spy->assertNoEvents();
7541 window->assertNoEvents();
7542}
7543
7544/**
7545 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7546 * be sent to other windows
7547 */
7548TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7549 auto spy = createSpy();
7550 spy->setFrame(Rect(0, 0, 100, 100));
7551 auto window = createForeground();
7552 window->setFrame(Rect(0, 0, 200, 200));
7553
7554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7555
7556 // First finger down on both window and spy
7557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7559 {10, 10}))
7560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7561 window->consumeMotionDown();
7562 spy->consumeMotionDown();
7563
7564 // Spy window pilfers the pointers.
7565 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7566 window->consumeMotionCancel();
7567
7568 // Second finger down on the window only
7569 const MotionEvent secondFingerDownEvent =
7570 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7571 .displayId(ADISPLAY_ID_DEFAULT)
7572 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7573 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7574 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7575 .x(150)
7576 .y(150))
7577 .build();
7578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7579 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7580 InputEventInjectionSync::WAIT_FOR_RESULT))
7581 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7582 window->consumeMotionDown();
7583 window->assertNoEvents();
7584
7585 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7586 spy->consumeMotionMove();
7587 spy->assertNoEvents();
7588}
7589
Prabir Pradhand65552b2021-10-07 11:23:50 -07007590class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7591public:
7592 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7593 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7594 std::make_shared<FakeApplicationHandle>();
7595 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007596 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7597 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007598 overlay->setFocusable(false);
7599 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007600 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007601 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007602 overlay->setTrustedOverlay(true);
7603
7604 std::shared_ptr<FakeApplicationHandle> application =
7605 std::make_shared<FakeApplicationHandle>();
7606 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007607 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7608 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007609 window->setFocusable(true);
7610 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007611
7612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7614 setFocusedWindow(window);
7615 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7616 return {std::move(overlay), std::move(window)};
7617 }
7618
7619 void sendFingerEvent(int32_t action) {
7620 NotifyMotionArgs motionArgs =
7621 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7622 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7623 mDispatcher->notifyMotion(&motionArgs);
7624 }
7625
7626 void sendStylusEvent(int32_t action) {
7627 NotifyMotionArgs motionArgs =
7628 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7629 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7630 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7631 mDispatcher->notifyMotion(&motionArgs);
7632 }
7633};
7634
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007635using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7636
7637TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7638 ScopedSilentDeath _silentDeath;
7639
Prabir Pradhand65552b2021-10-07 11:23:50 -07007640 auto [overlay, window] = setupStylusOverlayScenario();
7641 overlay->setTrustedOverlay(false);
7642 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7643 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7644 ".* not a trusted overlay");
7645}
7646
7647TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7648 auto [overlay, window] = setupStylusOverlayScenario();
7649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7650
7651 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7652 overlay->consumeMotionDown();
7653 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7654 overlay->consumeMotionUp();
7655
7656 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7657 window->consumeMotionDown();
7658 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7659 window->consumeMotionUp();
7660
7661 overlay->assertNoEvents();
7662 window->assertNoEvents();
7663}
7664
7665TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7666 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007667 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7669
7670 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7671 overlay->consumeMotionDown();
7672 window->consumeMotionDown();
7673 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7674 overlay->consumeMotionUp();
7675 window->consumeMotionUp();
7676
7677 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7678 window->consumeMotionDown();
7679 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7680 window->consumeMotionUp();
7681
7682 overlay->assertNoEvents();
7683 window->assertNoEvents();
7684}
7685
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007686/**
7687 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7688 * The scenario is as follows:
7689 * - The stylus interceptor overlay is configured as a spy window.
7690 * - The stylus interceptor spy receives the start of a new stylus gesture.
7691 * - It pilfers pointers and then configures itself to no longer be a spy.
7692 * - The stylus interceptor continues to receive the rest of the gesture.
7693 */
7694TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7695 auto [overlay, window] = setupStylusOverlayScenario();
7696 overlay->setSpy(true);
7697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7698
7699 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7700 overlay->consumeMotionDown();
7701 window->consumeMotionDown();
7702
7703 // The interceptor pilfers the pointers.
7704 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7705 window->consumeMotionCancel();
7706
7707 // The interceptor configures itself so that it is no longer a spy.
7708 overlay->setSpy(false);
7709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7710
7711 // It continues to receive the rest of the stylus gesture.
7712 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7713 overlay->consumeMotionMove();
7714 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7715 overlay->consumeMotionUp();
7716
7717 window->assertNoEvents();
7718}
7719
Prabir Pradhan5735a322022-04-11 17:23:34 +00007720struct User {
7721 int32_t mPid;
7722 int32_t mUid;
7723 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7724 std::unique_ptr<InputDispatcher>& mDispatcher;
7725
7726 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7727 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7728
7729 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7730 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7731 ADISPLAY_ID_DEFAULT, {100, 200},
7732 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7733 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7734 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7735 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7736 }
7737
7738 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7739 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7740 InputEventInjectionSync::WAIT_FOR_RESULT,
7741 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7742 mPolicyFlags);
7743 }
7744
7745 sp<FakeWindowHandle> createWindow() const {
7746 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7747 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007748 sp<FakeWindowHandle> window =
7749 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7750 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007751 window->setOwnerInfo(mPid, mUid);
7752 return window;
7753 }
7754};
7755
7756using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7757
7758TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7759 auto owner = User(mDispatcher, 10, 11);
7760 auto window = owner.createWindow();
7761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7762
7763 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7764 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7765 window->consumeMotionDown();
7766
7767 setFocusedWindow(window);
7768 window->consumeFocusEvent(true);
7769
7770 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7771 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7772 window->consumeKeyDown(ADISPLAY_ID_NONE);
7773}
7774
7775TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7776 auto owner = User(mDispatcher, 10, 11);
7777 auto window = owner.createWindow();
7778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7779
7780 auto rando = User(mDispatcher, 20, 21);
7781 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7782 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7783
7784 setFocusedWindow(window);
7785 window->consumeFocusEvent(true);
7786
7787 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7788 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7789 window->assertNoEvents();
7790}
7791
7792TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7793 auto owner = User(mDispatcher, 10, 11);
7794 auto window = owner.createWindow();
7795 auto spy = owner.createWindow();
7796 spy->setSpy(true);
7797 spy->setTrustedOverlay(true);
7798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7799
7800 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7801 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7802 spy->consumeMotionDown();
7803 window->consumeMotionDown();
7804}
7805
7806TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7807 auto owner = User(mDispatcher, 10, 11);
7808 auto window = owner.createWindow();
7809
7810 auto rando = User(mDispatcher, 20, 21);
7811 auto randosSpy = rando.createWindow();
7812 randosSpy->setSpy(true);
7813 randosSpy->setTrustedOverlay(true);
7814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7815
7816 // The event is targeted at owner's window, so injection should succeed, but the spy should
7817 // not receive the event.
7818 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7819 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7820 randosSpy->assertNoEvents();
7821 window->consumeMotionDown();
7822}
7823
7824TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7825 auto owner = User(mDispatcher, 10, 11);
7826 auto window = owner.createWindow();
7827
7828 auto rando = User(mDispatcher, 20, 21);
7829 auto randosSpy = rando.createWindow();
7830 randosSpy->setSpy(true);
7831 randosSpy->setTrustedOverlay(true);
7832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7833
7834 // A user that has injection permission can inject into any window.
7835 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7836 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7837 ADISPLAY_ID_DEFAULT));
7838 randosSpy->consumeMotionDown();
7839 window->consumeMotionDown();
7840
7841 setFocusedWindow(randosSpy);
7842 randosSpy->consumeFocusEvent(true);
7843
7844 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7845 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7846 window->assertNoEvents();
7847}
7848
7849TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7850 auto owner = User(mDispatcher, 10, 11);
7851 auto window = owner.createWindow();
7852
7853 auto rando = User(mDispatcher, 20, 21);
7854 auto randosWindow = rando.createWindow();
7855 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7856 randosWindow->setWatchOutsideTouch(true);
7857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7858
7859 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7860 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7861 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7862 window->consumeMotionDown();
7863 randosWindow->consumeMotionOutside();
7864}
7865
Garfield Tane84e6f92019-08-29 17:28:41 -07007866} // namespace android::inputdispatcher