blob: f3239caa6a5eeaccd6498c712f09654a2d2142b0 [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
Arthur Hung74c248d2022-11-23 07:09:59 +00001925TEST_F(InputDispatcherTest, WallpaperWindowReceivesMultiTouch) {
1926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1927 sp<FakeWindowHandle> window =
1928 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1929 window->setDupTouchToWallpaper(true);
1930
1931 sp<FakeWindowHandle> wallpaperWindow =
1932 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1933 wallpaperWindow->setIsWallpaper(true);
1934 constexpr int expectedWallpaperFlags =
1935 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1936 wallpaperWindow->setPreventSplitting(true);
1937
1938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1939
1940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1941 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1942 {50, 50}))
1943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1944 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1945 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1946
1947 const MotionEvent secondFingerDownEvent =
1948 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1949 .displayId(ADISPLAY_ID_DEFAULT)
1950 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1951 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
1952 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
1953 .build();
1954 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1955 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1956 InputEventInjectionSync::WAIT_FOR_RESULT))
1957 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1958
1959 window->consumeMotionPointerDown(1);
1960 wallpaperWindow->consumeMotionPointerDown(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1961
1962 const MotionEvent secondFingerUpEvent =
1963 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
1964 .displayId(ADISPLAY_ID_DEFAULT)
1965 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1966 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
1967 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
1968 .build();
1969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1970 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1971 InputEventInjectionSync::WAIT_FOR_RESULT))
1972 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1973 window->consumeMotionPointerUp(1);
1974 wallpaperWindow->consumeMotionPointerUp(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1975
1976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1977 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
1978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1979 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1980 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1981}
1982
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001983/**
1984 * On the display, have a single window, and also an area where there's no window.
1985 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1986 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1987 */
1988TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1989 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1990 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001991 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001992
1993 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1994 NotifyMotionArgs args;
1995
1996 // Touch down on the empty space
1997 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1998
1999 mDispatcher->waitForIdle();
2000 window->assertNoEvents();
2001
2002 // Now touch down on the window with another pointer
2003 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
2004 mDispatcher->waitForIdle();
2005 window->consumeMotionDown();
2006}
2007
2008/**
2009 * Same test as above, but instead of touching the empty space, the first touch goes to
2010 * non-touchable window.
2011 */
2012TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
2013 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2014 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002015 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002016 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2017 window1->setTouchable(false);
2018 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002019 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002020 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2021
2022 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2023
2024 NotifyMotionArgs args;
2025 // Touch down on the non-touchable window
2026 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2027
2028 mDispatcher->waitForIdle();
2029 window1->assertNoEvents();
2030 window2->assertNoEvents();
2031
2032 // Now touch down on the window with another pointer
2033 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2034 mDispatcher->waitForIdle();
2035 window2->consumeMotionDown();
2036}
2037
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002038/**
2039 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
2040 * to the event time of the first ACTION_DOWN sent to the particular window.
2041 */
2042TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
2043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2044 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002045 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002046 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
2047 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002048 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002049 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
2050
2051 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2052
2053 NotifyMotionArgs args;
2054 // Touch down on the first window
2055 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2056
2057 mDispatcher->waitForIdle();
2058 InputEvent* inputEvent1 = window1->consume();
2059 window2->assertNoEvents();
2060 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
2061 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
2062 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
2063
2064 // Now touch down on the window with another pointer
2065 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2066 mDispatcher->waitForIdle();
2067 InputEvent* inputEvent2 = window2->consume();
2068 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
2069 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
2070 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
2071 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
2072
2073 // Now move the pointer on the second window
2074 mDispatcher->notifyMotion(
2075 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
2076 mDispatcher->waitForIdle();
2077 InputEvent* inputEvent3 = window2->consume();
2078 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
2079 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
2080
2081 // Now add new touch down on the second window
2082 mDispatcher->notifyMotion(
2083 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
2084 mDispatcher->waitForIdle();
2085 InputEvent* inputEvent4 = window2->consume();
2086 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
2087 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
2088
2089 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2090 window1->consumeMotionMove();
2091 window1->assertNoEvents();
2092
2093 // Now move the pointer on the first window
2094 mDispatcher->notifyMotion(
2095 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2096 mDispatcher->waitForIdle();
2097 InputEvent* inputEvent5 = window1->consume();
2098 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2099 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2100
2101 mDispatcher->notifyMotion(&(
2102 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2103 mDispatcher->waitForIdle();
2104 InputEvent* inputEvent6 = window1->consume();
2105 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2106 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2107}
2108
Garfield Tandf26e862020-07-01 20:18:19 -07002109TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002110 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002111 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002112 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002113 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002114 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002115 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002116 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002117
2118 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2119
2120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2121
2122 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002124 injectMotionEvent(mDispatcher,
2125 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2126 AINPUT_SOURCE_MOUSE)
2127 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2128 .x(900)
2129 .y(400))
2130 .build()));
2131 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2132 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2133 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2134 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2135
2136 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002137 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002138 injectMotionEvent(mDispatcher,
2139 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2140 AINPUT_SOURCE_MOUSE)
2141 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2142 .x(300)
2143 .y(400))
2144 .build()));
2145 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2146 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2147 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2148 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2149 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2150 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2151
2152 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002154 injectMotionEvent(mDispatcher,
2155 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2156 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2157 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2158 .x(300)
2159 .y(400))
2160 .build()));
2161 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2162
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002164 injectMotionEvent(mDispatcher,
2165 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2166 AINPUT_SOURCE_MOUSE)
2167 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2168 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2169 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2170 .x(300)
2171 .y(400))
2172 .build()));
2173 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2174 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2175
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002177 injectMotionEvent(mDispatcher,
2178 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2179 AINPUT_SOURCE_MOUSE)
2180 .buttonState(0)
2181 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2182 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2183 .x(300)
2184 .y(400))
2185 .build()));
2186 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2187 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2188
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002189 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002190 injectMotionEvent(mDispatcher,
2191 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2192 .buttonState(0)
2193 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2194 .x(300)
2195 .y(400))
2196 .build()));
2197 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2198
2199 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002201 injectMotionEvent(mDispatcher,
2202 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2203 AINPUT_SOURCE_MOUSE)
2204 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2205 .x(900)
2206 .y(400))
2207 .build()));
2208 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2209 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2210 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2211 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2212 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2213 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2214}
2215
2216// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2217// directly in this test.
2218TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002219 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002220 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002221 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002222 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002223
2224 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2225
2226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
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_ENTER,
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_ENTER,
2237 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2238
2239 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002241 injectMotionEvent(mDispatcher,
2242 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2243 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2244 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2245 .x(300)
2246 .y(400))
2247 .build()));
2248 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2249
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002251 injectMotionEvent(mDispatcher,
2252 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2253 AINPUT_SOURCE_MOUSE)
2254 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2255 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2256 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2257 .x(300)
2258 .y(400))
2259 .build()));
2260 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2261 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2262
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002264 injectMotionEvent(mDispatcher,
2265 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2266 AINPUT_SOURCE_MOUSE)
2267 .buttonState(0)
2268 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2269 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2270 .x(300)
2271 .y(400))
2272 .build()));
2273 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2274 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2275
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002277 injectMotionEvent(mDispatcher,
2278 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2279 .buttonState(0)
2280 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2281 .x(300)
2282 .y(400))
2283 .build()));
2284 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2285
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002287 injectMotionEvent(mDispatcher,
2288 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2289 AINPUT_SOURCE_MOUSE)
2290 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2291 .x(300)
2292 .y(400))
2293 .build()));
2294 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2295 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2296}
2297
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002298/**
2299 * Inject a mouse hover event followed by a tap from touchscreen.
2300 * In the current implementation, the tap does not cause a HOVER_EXIT event.
2301 */
2302TEST_F(InputDispatcherTest, MouseHoverAndTouchTap) {
2303 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2304 sp<FakeWindowHandle> window =
2305 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2306 window->setFrame(Rect(0, 0, 100, 100));
2307
2308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2309
2310 // Inject a hover_move from mouse.
2311 NotifyMotionArgs motionArgs =
2312 generateMotionArgs(AMOTION_EVENT_ACTION_HOVER_MOVE, AINPUT_SOURCE_MOUSE,
2313 ADISPLAY_ID_DEFAULT, {{50, 50}});
2314 motionArgs.xCursorPosition = 50;
2315 motionArgs.yCursorPosition = 50;
2316 mDispatcher->notifyMotion(&motionArgs);
2317 ASSERT_NO_FATAL_FAILURE(
2318 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2319 WithSource(AINPUT_SOURCE_MOUSE))));
2320 ASSERT_NO_FATAL_FAILURE(
2321 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2322 WithSource(AINPUT_SOURCE_MOUSE))));
2323
2324 // Tap on the window
2325 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2326 ADISPLAY_ID_DEFAULT, {{10, 10}});
2327 mDispatcher->notifyMotion(&motionArgs);
2328 ASSERT_NO_FATAL_FAILURE(
2329 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2330 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2331
2332 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2333 ADISPLAY_ID_DEFAULT, {{10, 10}});
2334 mDispatcher->notifyMotion(&motionArgs);
2335 ASSERT_NO_FATAL_FAILURE(
2336 window->consumeMotionEvent(AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2337 WithSource(AINPUT_SOURCE_TOUCHSCREEN))));
2338}
2339
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02002340TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2341 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2342 sp<FakeWindowHandle> windowDefaultDisplay =
2343 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2344 ADISPLAY_ID_DEFAULT);
2345 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2346 sp<FakeWindowHandle> windowSecondDisplay =
2347 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2348 SECOND_DISPLAY_ID);
2349 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2350
2351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2352 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2353
2354 // Set cursor position in window in default display and check that hover enter and move
2355 // events are generated.
2356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2357 injectMotionEvent(mDispatcher,
2358 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2359 AINPUT_SOURCE_MOUSE)
2360 .displayId(ADISPLAY_ID_DEFAULT)
2361 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2362 .x(300)
2363 .y(600))
2364 .build()));
2365 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2366 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2367 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2368 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2369
2370 // Remove all windows in secondary display and check that no event happens on window in
2371 // primary display.
2372 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
2373 windowDefaultDisplay->assertNoEvents();
2374
2375 // Move cursor position in window in default display and check that only hover move
2376 // event is generated and not hover enter event.
2377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2378 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2380 injectMotionEvent(mDispatcher,
2381 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2382 AINPUT_SOURCE_MOUSE)
2383 .displayId(ADISPLAY_ID_DEFAULT)
2384 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2385 .x(400)
2386 .y(700))
2387 .build()));
2388 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2389 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2390 windowDefaultDisplay->assertNoEvents();
2391}
2392
Garfield Tan00f511d2019-06-12 16:55:40 -07002393TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002394 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002395
2396 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002397 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002398 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002399 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002400 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002401 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002402
2403 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2404
Arthur Hung72d8dc32020-03-28 00:48:39 +00002405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002406
2407 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2408 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002410 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002411 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002412 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002413 windowRight->assertNoEvents();
2414}
2415
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002416TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002417 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002418 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2419 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002420 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002421
Arthur Hung72d8dc32020-03-28 00:48:39 +00002422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002423 setFocusedWindow(window);
2424
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002425 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002426
2427 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2428 mDispatcher->notifyKey(&keyArgs);
2429
2430 // Window should receive key down event.
2431 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2432
2433 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2434 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002435 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002436 mDispatcher->notifyDeviceReset(&args);
2437 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2438 AKEY_EVENT_FLAG_CANCELED);
2439}
2440
2441TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002442 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002443 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2444 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002445
Arthur Hung72d8dc32020-03-28 00:48:39 +00002446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002447
2448 NotifyMotionArgs motionArgs =
2449 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2450 ADISPLAY_ID_DEFAULT);
2451 mDispatcher->notifyMotion(&motionArgs);
2452
2453 // Window should receive motion down event.
2454 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2455
2456 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2457 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002458 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002459 mDispatcher->notifyDeviceReset(&args);
2460 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2461 0 /*expectedFlags*/);
2462}
2463
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002464TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2465 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002466 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2467 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002468 window->setFocusable(true);
2469
2470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2471 setFocusedWindow(window);
2472
2473 window->consumeFocusEvent(true);
2474
2475 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2476 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2477 const nsecs_t injectTime = keyArgs.eventTime;
2478 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2479 mDispatcher->notifyKey(&keyArgs);
2480 // The dispatching time should be always greater than or equal to intercept key timeout.
2481 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2482 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2483 std::chrono::nanoseconds(interceptKeyTimeout).count());
2484}
2485
2486TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002488 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2489 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002490 window->setFocusable(true);
2491
2492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2493 setFocusedWindow(window);
2494
2495 window->consumeFocusEvent(true);
2496
2497 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2498 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2499 mFakePolicy->setInterceptKeyTimeout(150ms);
2500 mDispatcher->notifyKey(&keyDown);
2501 mDispatcher->notifyKey(&keyUp);
2502
2503 // Window should receive key event immediately when same key up.
2504 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2505 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2506}
2507
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002508/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002509 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2510 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2511 * ACTION_OUTSIDE event is sent per gesture.
2512 */
2513TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2514 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2515 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002516 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2517 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002518 window->setWatchOutsideTouch(true);
2519 window->setFrame(Rect{0, 0, 100, 100});
2520 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002521 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2522 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002523 secondWindow->setFrame(Rect{100, 100, 200, 200});
2524 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002525 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2526 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002527 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2529
2530 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2531 NotifyMotionArgs motionArgs =
2532 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2533 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2534 mDispatcher->notifyMotion(&motionArgs);
2535 window->assertNoEvents();
2536 secondWindow->assertNoEvents();
2537
2538 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2539 // Now, `window` should get ACTION_OUTSIDE.
2540 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2541 {PointF{-10, -10}, PointF{105, 105}});
2542 mDispatcher->notifyMotion(&motionArgs);
2543 window->consumeMotionOutside();
2544 secondWindow->consumeMotionDown();
2545 thirdWindow->assertNoEvents();
2546
2547 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2548 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2549 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2550 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2551 mDispatcher->notifyMotion(&motionArgs);
2552 window->assertNoEvents();
2553 secondWindow->consumeMotionMove();
2554 thirdWindow->consumeMotionDown();
2555}
2556
Prabir Pradhan814fe082022-07-22 20:22:18 +00002557TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2558 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002559 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2560 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002561 window->setFocusable(true);
2562
2563 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2564 setFocusedWindow(window);
2565
2566 window->consumeFocusEvent(true);
2567
2568 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2569 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2570 mDispatcher->notifyKey(&keyDown);
2571 mDispatcher->notifyKey(&keyUp);
2572
2573 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2574 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2575
2576 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2577 mDispatcher->onWindowInfosChanged({}, {});
2578
2579 window->consumeFocusEvent(false);
2580
2581 mDispatcher->notifyKey(&keyDown);
2582 mDispatcher->notifyKey(&keyUp);
2583 window->assertNoEvents();
2584}
2585
Arthur Hung96483742022-11-15 03:30:48 +00002586TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2588 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2589 "Fake Window", ADISPLAY_ID_DEFAULT);
2590 // Ensure window is non-split and have some transform.
2591 window->setPreventSplitting(true);
2592 window->setWindowOffset(20, 40);
2593 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2594
2595 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2596 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2597 {50, 50}))
2598 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2599 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2600
2601 const MotionEvent secondFingerDownEvent =
2602 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2603 .displayId(ADISPLAY_ID_DEFAULT)
2604 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2605 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2606 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2607 .x(-30)
2608 .y(-50))
2609 .build();
2610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2611 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2612 InputEventInjectionSync::WAIT_FOR_RESULT))
2613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2614
2615 const MotionEvent* event = window->consumeMotion();
2616 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2617 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2618 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2619 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2620 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2621}
2622
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002623/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002624 * Ensure the correct coordinate spaces are used by InputDispatcher.
2625 *
2626 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2627 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2628 * space.
2629 */
2630class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2631public:
2632 void SetUp() override {
2633 InputDispatcherTest::SetUp();
2634 mDisplayInfos.clear();
2635 mWindowInfos.clear();
2636 }
2637
2638 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2639 gui::DisplayInfo info;
2640 info.displayId = displayId;
2641 info.transform = transform;
2642 mDisplayInfos.push_back(std::move(info));
2643 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2644 }
2645
2646 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2647 mWindowInfos.push_back(*windowHandle->getInfo());
2648 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2649 }
2650
2651 // Set up a test scenario where the display has a scaled projection and there are two windows
2652 // on the display.
2653 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2654 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2655 // respectively.
2656 ui::Transform displayTransform;
2657 displayTransform.set(2, 0, 0, 4);
2658 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2659
2660 std::shared_ptr<FakeApplicationHandle> application =
2661 std::make_shared<FakeApplicationHandle>();
2662
2663 // Add two windows to the display. Their frames are represented in the display space.
2664 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002665 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2666 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002667 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2668 addWindow(firstWindow);
2669
2670 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002671 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2672 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002673 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2674 addWindow(secondWindow);
2675 return {std::move(firstWindow), std::move(secondWindow)};
2676 }
2677
2678private:
2679 std::vector<gui::DisplayInfo> mDisplayInfos;
2680 std::vector<gui::WindowInfo> mWindowInfos;
2681};
2682
2683TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2684 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2685 // Send down to the first window. The point is represented in the display space. The point is
2686 // selected so that if the hit test was done with the transform applied to it, then it would
2687 // end up in the incorrect window.
2688 NotifyMotionArgs downMotionArgs =
2689 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2690 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2691 mDispatcher->notifyMotion(&downMotionArgs);
2692
2693 firstWindow->consumeMotionDown();
2694 secondWindow->assertNoEvents();
2695}
2696
2697// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2698// the event should be treated as being in the logical display space.
2699TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2700 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2701 // Send down to the first window. The point is represented in the logical display space. The
2702 // point is selected so that if the hit test was done in logical display space, then it would
2703 // end up in the incorrect window.
2704 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2705 PointF{75 * 2, 55 * 4});
2706
2707 firstWindow->consumeMotionDown();
2708 secondWindow->assertNoEvents();
2709}
2710
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002711// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2712// event should be treated as being in the logical display space.
2713TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2714 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2715
2716 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2717 ui::Transform injectedEventTransform;
2718 injectedEventTransform.set(matrix);
2719 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2720 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2721
2722 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2723 .displayId(ADISPLAY_ID_DEFAULT)
2724 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2725 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2726 .x(untransformedPoint.x)
2727 .y(untransformedPoint.y))
2728 .build();
2729 event.transform(matrix);
2730
2731 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2732 InputEventInjectionSync::WAIT_FOR_RESULT);
2733
2734 firstWindow->consumeMotionDown();
2735 secondWindow->assertNoEvents();
2736}
2737
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002738TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2739 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2740
2741 // Send down to the second window.
2742 NotifyMotionArgs downMotionArgs =
2743 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2744 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2745 mDispatcher->notifyMotion(&downMotionArgs);
2746
2747 firstWindow->assertNoEvents();
2748 const MotionEvent* event = secondWindow->consumeMotion();
2749 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2750
2751 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2752 EXPECT_EQ(300, event->getRawX(0));
2753 EXPECT_EQ(880, event->getRawY(0));
2754
2755 // Ensure that the x and y values are in the window's coordinate space.
2756 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2757 // the logical display space. This will be the origin of the window space.
2758 EXPECT_EQ(100, event->getX(0));
2759 EXPECT_EQ(80, event->getY(0));
2760}
2761
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002762using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2763 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002764
2765class TransferTouchFixture : public InputDispatcherTest,
2766 public ::testing::WithParamInterface<TransferFunction> {};
2767
2768TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002769 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002770
2771 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002772 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002773 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2774 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002775 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002776 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2777 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002778
2779 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002781
2782 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002783 NotifyMotionArgs downMotionArgs =
2784 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2785 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002786 mDispatcher->notifyMotion(&downMotionArgs);
2787 // Only the first window should get the down event
2788 firstWindow->consumeMotionDown();
2789 secondWindow->assertNoEvents();
2790
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002791 // Transfer touch to the second window
2792 TransferFunction f = GetParam();
2793 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2794 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002795 // The first window gets cancel and the second gets down
2796 firstWindow->consumeMotionCancel();
2797 secondWindow->consumeMotionDown();
2798
2799 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002800 NotifyMotionArgs upMotionArgs =
2801 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2802 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002803 mDispatcher->notifyMotion(&upMotionArgs);
2804 // The first window gets no events and the second gets up
2805 firstWindow->assertNoEvents();
2806 secondWindow->consumeMotionUp();
2807}
2808
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002809/**
2810 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2811 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2812 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2813 * natural to the user.
2814 * In this test, we are sending a pointer to both spy window and first window. We then try to
2815 * transfer touch to the second window. The dispatcher should identify the first window as the
2816 * one that should lose the gesture, and therefore the action should be to move the gesture from
2817 * the first window to the second.
2818 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2819 * the other API, as well.
2820 */
2821TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2823
2824 // Create a couple of windows + a spy window
2825 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002826 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002827 spyWindow->setTrustedOverlay(true);
2828 spyWindow->setSpy(true);
2829 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002830 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002831 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002832 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002833
2834 // Add the windows to the dispatcher
2835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2836
2837 // Send down to the first window
2838 NotifyMotionArgs downMotionArgs =
2839 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2840 ADISPLAY_ID_DEFAULT);
2841 mDispatcher->notifyMotion(&downMotionArgs);
2842 // Only the first window and spy should get the down event
2843 spyWindow->consumeMotionDown();
2844 firstWindow->consumeMotionDown();
2845
2846 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2847 // if f === 'transferTouch'.
2848 TransferFunction f = GetParam();
2849 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2850 ASSERT_TRUE(success);
2851 // The first window gets cancel and the second gets down
2852 firstWindow->consumeMotionCancel();
2853 secondWindow->consumeMotionDown();
2854
2855 // Send up event to the second window
2856 NotifyMotionArgs upMotionArgs =
2857 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2858 ADISPLAY_ID_DEFAULT);
2859 mDispatcher->notifyMotion(&upMotionArgs);
2860 // The first window gets no events and the second+spy get up
2861 firstWindow->assertNoEvents();
2862 spyWindow->consumeMotionUp();
2863 secondWindow->consumeMotionUp();
2864}
2865
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002866TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002868
2869 PointF touchPoint = {10, 10};
2870
2871 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002872 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002873 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2874 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002875 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002876 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002877 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2878 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002879 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002880
2881 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002883
2884 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002885 NotifyMotionArgs downMotionArgs =
2886 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2887 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002888 mDispatcher->notifyMotion(&downMotionArgs);
2889 // Only the first window should get the down event
2890 firstWindow->consumeMotionDown();
2891 secondWindow->assertNoEvents();
2892
2893 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002894 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002895 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002896 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002897 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2898 // Only the first window should get the pointer down event
2899 firstWindow->consumeMotionPointerDown(1);
2900 secondWindow->assertNoEvents();
2901
2902 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002903 TransferFunction f = GetParam();
2904 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2905 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002906 // The first window gets cancel and the second gets down and pointer down
2907 firstWindow->consumeMotionCancel();
2908 secondWindow->consumeMotionDown();
2909 secondWindow->consumeMotionPointerDown(1);
2910
2911 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002912 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002913 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002914 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002915 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2916 // The first window gets nothing and the second gets pointer up
2917 firstWindow->assertNoEvents();
2918 secondWindow->consumeMotionPointerUp(1);
2919
2920 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002921 NotifyMotionArgs upMotionArgs =
2922 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2923 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002924 mDispatcher->notifyMotion(&upMotionArgs);
2925 // The first window gets nothing and the second gets up
2926 firstWindow->assertNoEvents();
2927 secondWindow->consumeMotionUp();
2928}
2929
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002930// For the cases of single pointer touch and two pointers non-split touch, the api's
2931// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2932// for the case where there are multiple pointers split across several windows.
2933INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2934 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002935 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2936 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002937 return dispatcher->transferTouch(destChannelToken,
2938 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002939 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002940 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2941 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002942 return dispatcher->transferTouchFocus(from, to,
2943 false /*isDragAndDrop*/);
2944 }));
2945
Svet Ganov5d3bc372020-01-26 23:11:07 -08002946TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002947 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002948
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002949 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002950 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2951 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002952 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002953
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002954 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002955 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2956 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002957 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002958
2959 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002961
2962 PointF pointInFirst = {300, 200};
2963 PointF pointInSecond = {300, 600};
2964
2965 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002966 NotifyMotionArgs firstDownMotionArgs =
2967 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2968 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002969 mDispatcher->notifyMotion(&firstDownMotionArgs);
2970 // Only the first window should get the down event
2971 firstWindow->consumeMotionDown();
2972 secondWindow->assertNoEvents();
2973
2974 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002975 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002976 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002977 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002978 mDispatcher->notifyMotion(&secondDownMotionArgs);
2979 // The first window gets a move and the second a down
2980 firstWindow->consumeMotionMove();
2981 secondWindow->consumeMotionDown();
2982
2983 // Transfer touch focus to the second window
2984 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2985 // The first window gets cancel and the new gets pointer down (it already saw down)
2986 firstWindow->consumeMotionCancel();
2987 secondWindow->consumeMotionPointerDown(1);
2988
2989 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002990 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002991 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002992 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002993 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2994 // The first window gets nothing and the second gets pointer up
2995 firstWindow->assertNoEvents();
2996 secondWindow->consumeMotionPointerUp(1);
2997
2998 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002999 NotifyMotionArgs upMotionArgs =
3000 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3001 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003002 mDispatcher->notifyMotion(&upMotionArgs);
3003 // The first window gets nothing and the second gets up
3004 firstWindow->assertNoEvents();
3005 secondWindow->consumeMotionUp();
3006}
3007
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003008// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3009// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3010// touch is not supported, so the touch should continue on those windows and the transferred-to
3011// window should get nothing.
3012TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3013 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3014
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003015 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003016 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3017 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003018 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003019
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003020 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003021 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3022 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003023 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003024
3025 // Add the windows to the dispatcher
3026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3027
3028 PointF pointInFirst = {300, 200};
3029 PointF pointInSecond = {300, 600};
3030
3031 // Send down to the first window
3032 NotifyMotionArgs firstDownMotionArgs =
3033 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3034 ADISPLAY_ID_DEFAULT, {pointInFirst});
3035 mDispatcher->notifyMotion(&firstDownMotionArgs);
3036 // Only the first window should get the down event
3037 firstWindow->consumeMotionDown();
3038 secondWindow->assertNoEvents();
3039
3040 // Send down to the second window
3041 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003042 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003043 {pointInFirst, pointInSecond});
3044 mDispatcher->notifyMotion(&secondDownMotionArgs);
3045 // The first window gets a move and the second a down
3046 firstWindow->consumeMotionMove();
3047 secondWindow->consumeMotionDown();
3048
3049 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003050 const bool transferred =
3051 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003052 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3053 ASSERT_FALSE(transferred);
3054 firstWindow->assertNoEvents();
3055 secondWindow->assertNoEvents();
3056
3057 // The rest of the dispatch should proceed as normal
3058 // Send pointer up to the second window
3059 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003060 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003061 {pointInFirst, pointInSecond});
3062 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3063 // The first window gets MOVE and the second gets pointer up
3064 firstWindow->consumeMotionMove();
3065 secondWindow->consumeMotionUp();
3066
3067 // Send up event to the first window
3068 NotifyMotionArgs upMotionArgs =
3069 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3070 ADISPLAY_ID_DEFAULT);
3071 mDispatcher->notifyMotion(&upMotionArgs);
3072 // The first window gets nothing and the second gets up
3073 firstWindow->consumeMotionUp();
3074 secondWindow->assertNoEvents();
3075}
3076
Arthur Hungabbb9d82021-09-01 14:52:30 +00003077// This case will create two windows and one mirrored window on the default display and mirror
3078// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3079// the windows info of second display before default display.
3080TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3081 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3082 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003083 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003084 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003085 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003086 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003087 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003088
3089 sp<FakeWindowHandle> mirrorWindowInPrimary =
3090 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3091 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003092
3093 sp<FakeWindowHandle> firstWindowInSecondary =
3094 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3095 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003096
3097 sp<FakeWindowHandle> secondWindowInSecondary =
3098 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3099 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003100
3101 // Update window info, let it find window handle of second display first.
3102 mDispatcher->setInputWindows(
3103 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3104 {ADISPLAY_ID_DEFAULT,
3105 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3106
3107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3108 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3109 {50, 50}))
3110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3111
3112 // Window should receive motion event.
3113 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3114
3115 // Transfer touch focus
3116 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3117 secondWindowInPrimary->getToken()));
3118 // The first window gets cancel.
3119 firstWindowInPrimary->consumeMotionCancel();
3120 secondWindowInPrimary->consumeMotionDown();
3121
3122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3123 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3124 ADISPLAY_ID_DEFAULT, {150, 50}))
3125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3126 firstWindowInPrimary->assertNoEvents();
3127 secondWindowInPrimary->consumeMotionMove();
3128
3129 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3130 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3131 {150, 50}))
3132 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3133 firstWindowInPrimary->assertNoEvents();
3134 secondWindowInPrimary->consumeMotionUp();
3135}
3136
3137// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3138// 'transferTouch' api.
3139TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3140 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3141 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003142 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003143 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003144 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003145 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00003146 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003147
3148 sp<FakeWindowHandle> mirrorWindowInPrimary =
3149 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3150 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003151
3152 sp<FakeWindowHandle> firstWindowInSecondary =
3153 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3154 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003155
3156 sp<FakeWindowHandle> secondWindowInSecondary =
3157 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3158 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003159
3160 // Update window info, let it find window handle of second display first.
3161 mDispatcher->setInputWindows(
3162 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3163 {ADISPLAY_ID_DEFAULT,
3164 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3165
3166 // Touch on second display.
3167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3168 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3169 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3170
3171 // Window should receive motion event.
3172 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3173
3174 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003175 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003176
3177 // The first window gets cancel.
3178 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3179 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3180
3181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3182 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3183 SECOND_DISPLAY_ID, {150, 50}))
3184 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3185 firstWindowInPrimary->assertNoEvents();
3186 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3187
3188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3189 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3190 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3191 firstWindowInPrimary->assertNoEvents();
3192 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3193}
3194
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003195TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003196 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003197 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3198 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003199
Vishnu Nair47074b82020-08-14 11:54:47 -07003200 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003202 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003203
3204 window->consumeFocusEvent(true);
3205
3206 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3207 mDispatcher->notifyKey(&keyArgs);
3208
3209 // Window should receive key down event.
3210 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3211}
3212
3213TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003214 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003215 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3216 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003217
Arthur Hung72d8dc32020-03-28 00:48:39 +00003218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003219
3220 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3221 mDispatcher->notifyKey(&keyArgs);
3222 mDispatcher->waitForIdle();
3223
3224 window->assertNoEvents();
3225}
3226
3227// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3228TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003229 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003230 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3231 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003232
Arthur Hung72d8dc32020-03-28 00:48:39 +00003233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003234
3235 // Send key
3236 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3237 mDispatcher->notifyKey(&keyArgs);
3238 // Send motion
3239 NotifyMotionArgs motionArgs =
3240 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3241 ADISPLAY_ID_DEFAULT);
3242 mDispatcher->notifyMotion(&motionArgs);
3243
3244 // Window should receive only the motion event
3245 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3246 window->assertNoEvents(); // Key event or focus event will not be received
3247}
3248
arthurhungea3f4fc2020-12-21 23:18:53 +08003249TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3250 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3251
arthurhungea3f4fc2020-12-21 23:18:53 +08003252 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003253 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3254 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003255 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003256
arthurhungea3f4fc2020-12-21 23:18:53 +08003257 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003258 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3259 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003260 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003261
3262 // Add the windows to the dispatcher
3263 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3264
3265 PointF pointInFirst = {300, 200};
3266 PointF pointInSecond = {300, 600};
3267
3268 // Send down to the first window
3269 NotifyMotionArgs firstDownMotionArgs =
3270 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3271 ADISPLAY_ID_DEFAULT, {pointInFirst});
3272 mDispatcher->notifyMotion(&firstDownMotionArgs);
3273 // Only the first window should get the down event
3274 firstWindow->consumeMotionDown();
3275 secondWindow->assertNoEvents();
3276
3277 // Send down to the second window
3278 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003279 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003280 {pointInFirst, pointInSecond});
3281 mDispatcher->notifyMotion(&secondDownMotionArgs);
3282 // The first window gets a move and the second a down
3283 firstWindow->consumeMotionMove();
3284 secondWindow->consumeMotionDown();
3285
3286 // Send pointer cancel to the second window
3287 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003288 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003289 {pointInFirst, pointInSecond});
3290 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3291 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3292 // The first window gets move and the second gets cancel.
3293 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3294 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3295
3296 // Send up event.
3297 NotifyMotionArgs upMotionArgs =
3298 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3299 ADISPLAY_ID_DEFAULT);
3300 mDispatcher->notifyMotion(&upMotionArgs);
3301 // The first window gets up and the second gets nothing.
3302 firstWindow->consumeMotionUp();
3303 secondWindow->assertNoEvents();
3304}
3305
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003306TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3307 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3308
3309 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003310 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3312 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3313 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3314 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3315
3316 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3317 window->assertNoEvents();
3318 mDispatcher->waitForIdle();
3319}
3320
chaviwd1c23182019-12-20 18:44:56 -08003321class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003322public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003323 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003324 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003325 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003326 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003327 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003328 }
3329
chaviwd1c23182019-12-20 18:44:56 -08003330 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3331
3332 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3333 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3334 expectedDisplayId, expectedFlags);
3335 }
3336
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003337 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3338
3339 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3340
chaviwd1c23182019-12-20 18:44:56 -08003341 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3342 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3343 expectedDisplayId, expectedFlags);
3344 }
3345
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003346 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3347 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3348 expectedDisplayId, expectedFlags);
3349 }
3350
chaviwd1c23182019-12-20 18:44:56 -08003351 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3352 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3353 expectedDisplayId, expectedFlags);
3354 }
3355
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003356 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3357 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3358 expectedDisplayId, expectedFlags);
3359 }
3360
Arthur Hungfbfa5722021-11-16 02:45:54 +00003361 void consumeMotionPointerDown(int32_t pointerIdx) {
3362 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3363 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3364 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3365 0 /*expectedFlags*/);
3366 }
3367
Evan Rosky84f07f02021-04-16 10:42:42 -07003368 MotionEvent* consumeMotion() {
3369 InputEvent* event = mInputReceiver->consume();
3370 if (!event) {
3371 ADD_FAILURE() << "No event was produced";
3372 return nullptr;
3373 }
3374 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3375 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3376 return nullptr;
3377 }
3378 return static_cast<MotionEvent*>(event);
3379 }
3380
chaviwd1c23182019-12-20 18:44:56 -08003381 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3382
3383private:
3384 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003385};
3386
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003387using InputDispatcherMonitorTest = InputDispatcherTest;
3388
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003389/**
3390 * Two entities that receive touch: A window, and a global monitor.
3391 * The touch goes to the window, and then the window disappears.
3392 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3393 * for the monitor, as well.
3394 * 1. foregroundWindow
3395 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3396 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003397TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003398 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3399 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003400 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003401
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003402 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003403
3404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3406 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3407 {100, 200}))
3408 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3409
3410 // Both the foreground window and the global monitor should receive the touch down
3411 window->consumeMotionDown();
3412 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3413
3414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3415 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3416 ADISPLAY_ID_DEFAULT, {110, 200}))
3417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3418
3419 window->consumeMotionMove();
3420 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3421
3422 // Now the foreground window goes away
3423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3424 window->consumeMotionCancel();
3425 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3426
3427 // If more events come in, there will be no more foreground window to send them to. This will
3428 // cause a cancel for the monitor, as well.
3429 ASSERT_EQ(InputEventInjectionResult::FAILED,
3430 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3431 ADISPLAY_ID_DEFAULT, {120, 200}))
3432 << "Injection should fail because the window was removed";
3433 window->assertNoEvents();
3434 // Global monitor now gets the cancel
3435 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3436}
3437
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003438TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
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 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003443
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003444 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003445
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003447 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003448 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003449 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003450 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003451}
3452
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003453TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3454 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003455
Chris Yea209fde2020-07-22 13:54:51 -07003456 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003457 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3458 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003464 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003465 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003466
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003467 // Pilfer pointers from the monitor.
3468 // This should not do anything and the window should continue to receive events.
3469 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003470
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003472 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3473 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003475
3476 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3477 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003478}
3479
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003480TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003481 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003482 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3483 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3485 window->setWindowOffset(20, 40);
3486 window->setWindowTransform(0, 1, -1, 0);
3487
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003488 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003489
3490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3491 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3492 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3493 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3494 MotionEvent* event = monitor.consumeMotion();
3495 // Even though window has transform, gesture monitor must not.
3496 ASSERT_EQ(ui::Transform(), event->getTransform());
3497}
3498
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003499TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003500 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003501 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003502
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003503 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003504 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003505 << "Injection should fail if there is a monitor, but no touchable window";
3506 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003507}
3508
chaviw81e2bb92019-12-18 15:03:51 -08003509TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003510 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003511 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3512 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003513
Arthur Hung72d8dc32020-03-28 00:48:39 +00003514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003515
3516 NotifyMotionArgs motionArgs =
3517 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3518 ADISPLAY_ID_DEFAULT);
3519
3520 mDispatcher->notifyMotion(&motionArgs);
3521 // Window should receive motion down event.
3522 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3523
3524 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003525 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003526 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3527 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3528 motionArgs.pointerCoords[0].getX() - 10);
3529
3530 mDispatcher->notifyMotion(&motionArgs);
3531 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3532 0 /*expectedFlags*/);
3533}
3534
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003535/**
3536 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3537 * the device default right away. In the test scenario, we check both the default value,
3538 * and the action of enabling / disabling.
3539 */
3540TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003541 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003542 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3543 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003544 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003545
3546 // Set focused application.
3547 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003548 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003549
3550 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003552 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003553 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3554
3555 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003556 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003558 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3559
3560 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003561 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003562 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003563 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003564 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003566 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003567 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3568
3569 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003570 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003572 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3573
3574 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003575 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003576 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003577 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003578 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003580 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003581 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3582
3583 window->assertNoEvents();
3584}
3585
Gang Wange9087892020-01-07 12:17:14 -05003586TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003588 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3589 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003590
3591 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003592 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003593
Arthur Hung72d8dc32020-03-28 00:48:39 +00003594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003595 setFocusedWindow(window);
3596
Gang Wange9087892020-01-07 12:17:14 -05003597 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3598
3599 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3600 mDispatcher->notifyKey(&keyArgs);
3601
3602 InputEvent* event = window->consume();
3603 ASSERT_NE(event, nullptr);
3604
3605 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3606 ASSERT_NE(verified, nullptr);
3607 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3608
3609 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3610 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3611 ASSERT_EQ(keyArgs.source, verified->source);
3612 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3613
3614 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3615
3616 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003617 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003618 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003619 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3620 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3621 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3622 ASSERT_EQ(0, verifiedKey.repeatCount);
3623}
3624
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003625TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003626 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003627 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3628 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003629
3630 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3631
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003632 ui::Transform transform;
3633 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3634
3635 gui::DisplayInfo displayInfo;
3636 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3637 displayInfo.transform = transform;
3638
3639 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003640
3641 NotifyMotionArgs motionArgs =
3642 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3643 ADISPLAY_ID_DEFAULT);
3644 mDispatcher->notifyMotion(&motionArgs);
3645
3646 InputEvent* event = window->consume();
3647 ASSERT_NE(event, nullptr);
3648
3649 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3650 ASSERT_NE(verified, nullptr);
3651 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3652
3653 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3654 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3655 EXPECT_EQ(motionArgs.source, verified->source);
3656 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3657
3658 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3659
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003660 const vec2 rawXY =
3661 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3662 motionArgs.pointerCoords[0].getXYValue());
3663 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3664 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003665 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003666 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003667 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003668 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3669 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3670}
3671
chaviw09c8d2d2020-08-24 15:48:26 -07003672/**
3673 * Ensure that separate calls to sign the same data are generating the same key.
3674 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3675 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3676 * tests.
3677 */
3678TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3679 KeyEvent event = getTestKeyEvent();
3680 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3681
3682 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3683 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3684 ASSERT_EQ(hmac1, hmac2);
3685}
3686
3687/**
3688 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3689 */
3690TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3691 KeyEvent event = getTestKeyEvent();
3692 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3693 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3694
3695 verifiedEvent.deviceId += 1;
3696 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3697
3698 verifiedEvent.source += 1;
3699 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3700
3701 verifiedEvent.eventTimeNanos += 1;
3702 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3703
3704 verifiedEvent.displayId += 1;
3705 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3706
3707 verifiedEvent.action += 1;
3708 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3709
3710 verifiedEvent.downTimeNanos += 1;
3711 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3712
3713 verifiedEvent.flags += 1;
3714 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3715
3716 verifiedEvent.keyCode += 1;
3717 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3718
3719 verifiedEvent.scanCode += 1;
3720 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3721
3722 verifiedEvent.metaState += 1;
3723 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3724
3725 verifiedEvent.repeatCount += 1;
3726 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3727}
3728
Vishnu Nair958da932020-08-21 17:12:37 -07003729TEST_F(InputDispatcherTest, SetFocusedWindow) {
3730 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3731 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003732 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003733 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003734 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003735 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3736
3737 // Top window is also focusable but is not granted focus.
3738 windowTop->setFocusable(true);
3739 windowSecond->setFocusable(true);
3740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3741 setFocusedWindow(windowSecond);
3742
3743 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003744 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3745 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003746
3747 // Focused window should receive event.
3748 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3749 windowTop->assertNoEvents();
3750}
3751
3752TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3753 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3754 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003755 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003756 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3757
3758 window->setFocusable(true);
3759 // Release channel for window is no longer valid.
3760 window->releaseChannel();
3761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3762 setFocusedWindow(window);
3763
3764 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003765 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3766 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003767
3768 // window channel is invalid, so it should not receive any input event.
3769 window->assertNoEvents();
3770}
3771
3772TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3773 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3774 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003775 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003776 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003777 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3778
Vishnu Nair958da932020-08-21 17:12:37 -07003779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3780 setFocusedWindow(window);
3781
3782 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003783 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3784 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003785
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003786 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003787 window->assertNoEvents();
3788}
3789
3790TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3791 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3792 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003793 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003794 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003795 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003796 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3797
3798 windowTop->setFocusable(true);
3799 windowSecond->setFocusable(true);
3800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3801 setFocusedWindow(windowTop);
3802 windowTop->consumeFocusEvent(true);
3803
3804 setFocusedWindow(windowSecond, windowTop);
3805 windowSecond->consumeFocusEvent(true);
3806 windowTop->consumeFocusEvent(false);
3807
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003808 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3809 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003810
3811 // Focused window should receive event.
3812 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3813}
3814
3815TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3816 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3817 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003818 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003819 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003820 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003821 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3822
3823 windowTop->setFocusable(true);
3824 windowSecond->setFocusable(true);
3825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3826 setFocusedWindow(windowSecond, windowTop);
3827
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003828 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3829 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003830
3831 // Event should be dropped.
3832 windowTop->assertNoEvents();
3833 windowSecond->assertNoEvents();
3834}
3835
3836TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3837 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3838 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003839 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003840 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003841 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3842 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003843 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3844
3845 window->setFocusable(true);
3846 previousFocusedWindow->setFocusable(true);
3847 window->setVisible(false);
3848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3849 setFocusedWindow(previousFocusedWindow);
3850 previousFocusedWindow->consumeFocusEvent(true);
3851
3852 // Requesting focus on invisible window takes focus from currently focused window.
3853 setFocusedWindow(window);
3854 previousFocusedWindow->consumeFocusEvent(false);
3855
3856 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003858 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003859 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003860
3861 // Window does not get focus event or key down.
3862 window->assertNoEvents();
3863
3864 // Window becomes visible.
3865 window->setVisible(true);
3866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3867
3868 // Window receives focus event.
3869 window->consumeFocusEvent(true);
3870 // Focused window receives key down.
3871 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3872}
3873
Vishnu Nair599f1412021-06-21 10:39:58 -07003874TEST_F(InputDispatcherTest, DisplayRemoved) {
3875 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3876 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003877 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003878 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3879
3880 // window is granted focus.
3881 window->setFocusable(true);
3882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3883 setFocusedWindow(window);
3884 window->consumeFocusEvent(true);
3885
3886 // When a display is removed window loses focus.
3887 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3888 window->consumeFocusEvent(false);
3889}
3890
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003891/**
3892 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3893 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3894 * of the 'slipperyEnterWindow'.
3895 *
3896 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3897 * a way so that the touched location is no longer covered by the top window.
3898 *
3899 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3900 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3901 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3902 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3903 * with ACTION_DOWN).
3904 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3905 * window moved itself away from the touched location and had Flag::SLIPPERY.
3906 *
3907 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3908 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3909 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3910 *
3911 * In this test, we ensure that the event received by the bottom window has
3912 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3913 */
3914TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003915 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3916 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003917
3918 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3919 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3920
3921 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003922 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003923 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003924 // Make sure this one overlaps the bottom window
3925 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3926 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3927 // one. Windows with the same owner are not considered to be occluding each other.
3928 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3929
3930 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003931 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003932 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3933
3934 mDispatcher->setInputWindows(
3935 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3936
3937 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3938 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3939 ADISPLAY_ID_DEFAULT, {{50, 50}});
3940 mDispatcher->notifyMotion(&args);
3941 slipperyExitWindow->consumeMotionDown();
3942 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3943 mDispatcher->setInputWindows(
3944 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3945
3946 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3947 ADISPLAY_ID_DEFAULT, {{51, 51}});
3948 mDispatcher->notifyMotion(&args);
3949
3950 slipperyExitWindow->consumeMotionCancel();
3951
3952 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3953 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3954}
3955
Garfield Tan1c7bc862020-01-28 13:24:04 -08003956class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3957protected:
3958 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3959 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3960
Chris Yea209fde2020-07-22 13:54:51 -07003961 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003962 sp<FakeWindowHandle> mWindow;
3963
3964 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003965 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003966 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003967 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003968 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3969 ASSERT_EQ(OK, mDispatcher->start());
3970
3971 setUpWindow();
3972 }
3973
3974 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003975 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003976 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003977
Vishnu Nair47074b82020-08-14 11:54:47 -07003978 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003980 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003981 mWindow->consumeFocusEvent(true);
3982 }
3983
Chris Ye2ad95392020-09-01 13:44:44 -07003984 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003985 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003986 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003987 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3988 mDispatcher->notifyKey(&keyArgs);
3989
3990 // Window should receive key down event.
3991 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3992 }
3993
3994 void expectKeyRepeatOnce(int32_t repeatCount) {
3995 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3996 InputEvent* repeatEvent = mWindow->consume();
3997 ASSERT_NE(nullptr, repeatEvent);
3998
3999 uint32_t eventType = repeatEvent->getType();
4000 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
4001
4002 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
4003 uint32_t eventAction = repeatKeyEvent->getAction();
4004 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
4005 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4006 }
4007
Chris Ye2ad95392020-09-01 13:44:44 -07004008 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004009 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004010 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004011 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4012 mDispatcher->notifyKey(&keyArgs);
4013
4014 // Window should receive key down event.
4015 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
4016 0 /*expectedFlags*/);
4017 }
4018};
4019
4020TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07004021 sendAndConsumeKeyDown(1 /* deviceId */);
4022 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4023 expectKeyRepeatOnce(repeatCount);
4024 }
4025}
4026
4027TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
4028 sendAndConsumeKeyDown(1 /* deviceId */);
4029 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4030 expectKeyRepeatOnce(repeatCount);
4031 }
4032 sendAndConsumeKeyDown(2 /* deviceId */);
4033 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004034 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4035 expectKeyRepeatOnce(repeatCount);
4036 }
4037}
4038
4039TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07004040 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004041 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07004042 sendAndConsumeKeyUp(1 /* deviceId */);
4043 mWindow->assertNoEvents();
4044}
4045
4046TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
4047 sendAndConsumeKeyDown(1 /* deviceId */);
4048 expectKeyRepeatOnce(1 /*repeatCount*/);
4049 sendAndConsumeKeyDown(2 /* deviceId */);
4050 expectKeyRepeatOnce(1 /*repeatCount*/);
4051 // Stale key up from device 1.
4052 sendAndConsumeKeyUp(1 /* deviceId */);
4053 // Device 2 is still down, keep repeating
4054 expectKeyRepeatOnce(2 /*repeatCount*/);
4055 expectKeyRepeatOnce(3 /*repeatCount*/);
4056 // Device 2 key up
4057 sendAndConsumeKeyUp(2 /* deviceId */);
4058 mWindow->assertNoEvents();
4059}
4060
4061TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
4062 sendAndConsumeKeyDown(1 /* deviceId */);
4063 expectKeyRepeatOnce(1 /*repeatCount*/);
4064 sendAndConsumeKeyDown(2 /* deviceId */);
4065 expectKeyRepeatOnce(1 /*repeatCount*/);
4066 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
4067 sendAndConsumeKeyUp(2 /* deviceId */);
4068 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004069 mWindow->assertNoEvents();
4070}
4071
liushenxiang42232912021-05-21 20:24:09 +08004072TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4073 sendAndConsumeKeyDown(DEVICE_ID);
4074 expectKeyRepeatOnce(1 /*repeatCount*/);
4075 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
4076 mDispatcher->notifyDeviceReset(&args);
4077 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4078 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4079 mWindow->assertNoEvents();
4080}
4081
Garfield Tan1c7bc862020-01-28 13:24:04 -08004082TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004083 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004084 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4085 InputEvent* repeatEvent = mWindow->consume();
4086 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4087 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4088 IdGenerator::getSource(repeatEvent->getId()));
4089 }
4090}
4091
4092TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004093 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004094
4095 std::unordered_set<int32_t> idSet;
4096 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4097 InputEvent* repeatEvent = mWindow->consume();
4098 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4099 int32_t id = repeatEvent->getId();
4100 EXPECT_EQ(idSet.end(), idSet.find(id));
4101 idSet.insert(id);
4102 }
4103}
4104
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004105/* Test InputDispatcher for MultiDisplay */
4106class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4107public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004108 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004109 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004110
Chris Yea209fde2020-07-22 13:54:51 -07004111 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004112 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004113 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004114
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004115 // Set focus window for primary display, but focused display would be second one.
4116 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004117 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004119 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004120 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004121
Chris Yea209fde2020-07-22 13:54:51 -07004122 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004123 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004124 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004125 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004126 // Set focus display to second one.
4127 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4128 // Set focus window for second display.
4129 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004130 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004131 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004132 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004133 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004134 }
4135
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004136 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004137 InputDispatcherTest::TearDown();
4138
Chris Yea209fde2020-07-22 13:54:51 -07004139 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004140 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004141 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004142 windowInSecondary.clear();
4143 }
4144
4145protected:
Chris Yea209fde2020-07-22 13:54:51 -07004146 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004147 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004148 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004149 sp<FakeWindowHandle> windowInSecondary;
4150};
4151
4152TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4153 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4155 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004157 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004158 windowInSecondary->assertNoEvents();
4159
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004160 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4162 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4163 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004164 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004165 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004166}
4167
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004168TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004169 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4171 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004172 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004173 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004174 windowInSecondary->assertNoEvents();
4175
4176 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004178 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004179 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004180 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004181
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004182 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004183 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004184
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004186 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4187 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004188
4189 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004190 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004191 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004192 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004193 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004194 windowInSecondary->assertNoEvents();
4195}
4196
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004197// Test per-display input monitors for motion event.
4198TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004199 FakeMonitorReceiver monitorInPrimary =
4200 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4201 FakeMonitorReceiver monitorInSecondary =
4202 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004203
4204 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4206 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4207 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004208 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004209 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004210 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004211 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004212
4213 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4215 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4216 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004217 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004218 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004219 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004220 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004221
4222 // Test inject a non-pointer motion event.
4223 // If specific a display, it will dispatch to the focused window of particular display,
4224 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004225 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4226 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4227 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004228 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004229 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004230 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004231 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004232}
4233
4234// Test per-display input monitors for key event.
4235TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004236 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004237 FakeMonitorReceiver monitorInPrimary =
4238 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4239 FakeMonitorReceiver monitorInSecondary =
4240 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004241
4242 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4244 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004245 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004246 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004247 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004248 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004249}
4250
Vishnu Nair958da932020-08-21 17:12:37 -07004251TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4252 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004253 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004254 secondWindowInPrimary->setFocusable(true);
4255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4256 setFocusedWindow(secondWindowInPrimary);
4257 windowInPrimary->consumeFocusEvent(false);
4258 secondWindowInPrimary->consumeFocusEvent(true);
4259
4260 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4262 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004263 windowInPrimary->assertNoEvents();
4264 windowInSecondary->assertNoEvents();
4265 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4266}
4267
Arthur Hungdfd528e2021-12-08 13:23:04 +00004268TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4269 FakeMonitorReceiver monitorInPrimary =
4270 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4271 FakeMonitorReceiver monitorInSecondary =
4272 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4273
4274 // Test touch down on primary display.
4275 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4276 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4277 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4278 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4279 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4280
4281 // Test touch down on second display.
4282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4283 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4284 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4285 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4286 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4287
4288 // Trigger cancel touch.
4289 mDispatcher->cancelCurrentTouch();
4290 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4291 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4292 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4293 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4294
4295 // Test inject a move motion event, no window/monitor should receive the event.
4296 ASSERT_EQ(InputEventInjectionResult::FAILED,
4297 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4298 ADISPLAY_ID_DEFAULT, {110, 200}))
4299 << "Inject motion event should return InputEventInjectionResult::FAILED";
4300 windowInPrimary->assertNoEvents();
4301 monitorInPrimary.assertNoEvents();
4302
4303 ASSERT_EQ(InputEventInjectionResult::FAILED,
4304 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4305 SECOND_DISPLAY_ID, {110, 200}))
4306 << "Inject motion event should return InputEventInjectionResult::FAILED";
4307 windowInSecondary->assertNoEvents();
4308 monitorInSecondary.assertNoEvents();
4309}
4310
Jackal Guof9696682018-10-05 12:23:23 +08004311class InputFilterTest : public InputDispatcherTest {
4312protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004313 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4314 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004315 NotifyMotionArgs motionArgs;
4316
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004317 motionArgs =
4318 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004319 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004320 motionArgs =
4321 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004322 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004323 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004324 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004325 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4326 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004327 } else {
4328 mFakePolicy->assertFilterInputEventWasNotCalled();
4329 }
4330 }
4331
4332 void testNotifyKey(bool expectToBeFiltered) {
4333 NotifyKeyArgs keyArgs;
4334
4335 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4336 mDispatcher->notifyKey(&keyArgs);
4337 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4338 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004339 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004340
4341 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004342 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004343 } else {
4344 mFakePolicy->assertFilterInputEventWasNotCalled();
4345 }
4346 }
4347};
4348
4349// Test InputFilter for MotionEvent
4350TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4351 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4352 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4353 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4354
4355 // Enable InputFilter
4356 mDispatcher->setInputFilterEnabled(true);
4357 // Test touch on both primary and second display, and check if both events are filtered.
4358 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4359 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4360
4361 // Disable InputFilter
4362 mDispatcher->setInputFilterEnabled(false);
4363 // Test touch on both primary and second display, and check if both events aren't filtered.
4364 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4365 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4366}
4367
4368// Test InputFilter for KeyEvent
4369TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4370 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4371 testNotifyKey(/*expectToBeFiltered*/ false);
4372
4373 // Enable InputFilter
4374 mDispatcher->setInputFilterEnabled(true);
4375 // Send a key event, and check if it is filtered.
4376 testNotifyKey(/*expectToBeFiltered*/ true);
4377
4378 // Disable InputFilter
4379 mDispatcher->setInputFilterEnabled(false);
4380 // Send a key event, and check if it isn't filtered.
4381 testNotifyKey(/*expectToBeFiltered*/ false);
4382}
4383
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004384// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4385// logical display coordinate space.
4386TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4387 ui::Transform firstDisplayTransform;
4388 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4389 ui::Transform secondDisplayTransform;
4390 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4391
4392 std::vector<gui::DisplayInfo> displayInfos(2);
4393 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4394 displayInfos[0].transform = firstDisplayTransform;
4395 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4396 displayInfos[1].transform = secondDisplayTransform;
4397
4398 mDispatcher->onWindowInfosChanged({}, displayInfos);
4399
4400 // Enable InputFilter
4401 mDispatcher->setInputFilterEnabled(true);
4402
4403 // Ensure the correct transforms are used for the displays.
4404 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4405 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4406}
4407
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004408class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4409protected:
4410 virtual void SetUp() override {
4411 InputDispatcherTest::SetUp();
4412
4413 /**
4414 * We don't need to enable input filter to test the injected event policy, but we enabled it
4415 * here to make the tests more realistic, since this policy only matters when inputfilter is
4416 * on.
4417 */
4418 mDispatcher->setInputFilterEnabled(true);
4419
4420 std::shared_ptr<InputApplicationHandle> application =
4421 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004422 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4423 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004424
4425 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4426 mWindow->setFocusable(true);
4427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4428 setFocusedWindow(mWindow);
4429 mWindow->consumeFocusEvent(true);
4430 }
4431
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004432 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4433 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004434 KeyEvent event;
4435
4436 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4437 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4438 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4439 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4440 const int32_t additionalPolicyFlags =
4441 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4442 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004443 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004444 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4445 policyFlags | additionalPolicyFlags));
4446
4447 InputEvent* received = mWindow->consume();
4448 ASSERT_NE(nullptr, received);
4449 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004450 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4451 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4452 ASSERT_EQ(flags, keyEvent.getFlags());
4453 }
4454
4455 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4456 int32_t flags) {
4457 MotionEvent event;
4458 PointerProperties pointerProperties[1];
4459 PointerCoords pointerCoords[1];
4460 pointerProperties[0].clear();
4461 pointerProperties[0].id = 0;
4462 pointerCoords[0].clear();
4463 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4464 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4465
4466 ui::Transform identityTransform;
4467 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4468 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4469 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4470 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4471 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004472 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004473 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004474 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4475
4476 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004478 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004479 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4480 policyFlags | additionalPolicyFlags));
4481
4482 InputEvent* received = mWindow->consume();
4483 ASSERT_NE(nullptr, received);
4484 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4485 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4486 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4487 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004488 }
4489
4490private:
4491 sp<FakeWindowHandle> mWindow;
4492};
4493
4494TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004495 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4496 // filter. Without it, the event will no different from a regularly injected event, and the
4497 // injected device id will be overwritten.
4498 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4499 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004500}
4501
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004502TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004503 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004504 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4505 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4506}
4507
4508TEST_F(InputFilterInjectionPolicyTest,
4509 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4510 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4511 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4512 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004513}
4514
4515TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4516 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004517 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004518}
4519
chaviwfd6d3512019-03-25 13:23:49 -07004520class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004521 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004522 InputDispatcherTest::SetUp();
4523
Chris Yea209fde2020-07-22 13:54:51 -07004524 std::shared_ptr<FakeApplicationHandle> application =
4525 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004526 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004527 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004528 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004529
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004530 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004531 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004532 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004533
4534 // Set focused application.
4535 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004536 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004537
4538 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004540 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004541 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004542 }
4543
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004544 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004545 InputDispatcherTest::TearDown();
4546
4547 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004548 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004549 }
4550
4551protected:
4552 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004553 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004554 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004555};
4556
4557// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4558// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4559// the onPointerDownOutsideFocus callback.
4560TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004562 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4563 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004565 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004566
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004567 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004568 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4569}
4570
4571// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4572// DOWN on the window that doesn't have focus. Ensure no window received the
4573// onPointerDownOutsideFocus callback.
4574TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004576 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004578 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004579
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004580 ASSERT_TRUE(mDispatcher->waitForIdle());
4581 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004582}
4583
4584// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4585// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4586TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4588 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004589 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004590 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004591
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004592 ASSERT_TRUE(mDispatcher->waitForIdle());
4593 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004594}
4595
4596// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4597// DOWN on the window that already has focus. Ensure no window received the
4598// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004599TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004602 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004603 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004604 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004605
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004606 ASSERT_TRUE(mDispatcher->waitForIdle());
4607 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004608}
4609
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004610// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4611// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4612TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4613 const MotionEvent event =
4614 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4615 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4616 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4617 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4618 .build();
4619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4621 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4622
4623 ASSERT_TRUE(mDispatcher->waitForIdle());
4624 mFakePolicy->assertOnPointerDownWasNotCalled();
4625 // Ensure that the unfocused window did not receive any FOCUS events.
4626 mUnfocusedWindow->assertNoEvents();
4627}
4628
chaviwaf87b3e2019-10-01 16:59:28 -07004629// These tests ensures we can send touch events to a single client when there are multiple input
4630// windows that point to the same client token.
4631class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4632 virtual void SetUp() override {
4633 InputDispatcherTest::SetUp();
4634
Chris Yea209fde2020-07-22 13:54:51 -07004635 std::shared_ptr<FakeApplicationHandle> application =
4636 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004637 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4638 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004639 mWindow1->setFrame(Rect(0, 0, 100, 100));
4640
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004641 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4642 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004643 mWindow2->setFrame(Rect(100, 100, 200, 200));
4644
Arthur Hung72d8dc32020-03-28 00:48:39 +00004645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004646 }
4647
4648protected:
4649 sp<FakeWindowHandle> mWindow1;
4650 sp<FakeWindowHandle> mWindow2;
4651
4652 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004653 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004654 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4655 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004656 }
4657
4658 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4659 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004660 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004661 InputEvent* event = window->consume();
4662
4663 ASSERT_NE(nullptr, event) << name.c_str()
4664 << ": consumer should have returned non-NULL event.";
4665
4666 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4667 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4668 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4669
4670 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004671 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004672
4673 for (size_t i = 0; i < points.size(); i++) {
4674 float expectedX = points[i].x;
4675 float expectedY = points[i].y;
4676
4677 EXPECT_EQ(expectedX, motionEvent.getX(i))
4678 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4679 << ", got " << motionEvent.getX(i);
4680 EXPECT_EQ(expectedY, motionEvent.getY(i))
4681 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4682 << ", got " << motionEvent.getY(i);
4683 }
4684 }
chaviw9eaa22c2020-07-01 16:21:27 -07004685
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004686 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004687 std::vector<PointF> expectedPoints) {
4688 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4689 ADISPLAY_ID_DEFAULT, touchedPoints);
4690 mDispatcher->notifyMotion(&motionArgs);
4691
4692 // Always consume from window1 since it's the window that has the InputReceiver
4693 consumeMotionEvent(mWindow1, action, expectedPoints);
4694 }
chaviwaf87b3e2019-10-01 16:59:28 -07004695};
4696
4697TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4698 // Touch Window 1
4699 PointF touchedPoint = {10, 10};
4700 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004701 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004702
4703 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004704 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004705
4706 // Touch Window 2
4707 touchedPoint = {150, 150};
4708 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004709 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004710}
4711
chaviw9eaa22c2020-07-01 16:21:27 -07004712TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4713 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004714 mWindow2->setWindowScale(0.5f, 0.5f);
4715
4716 // Touch Window 1
4717 PointF touchedPoint = {10, 10};
4718 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004719 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004720 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004721 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004722
4723 // Touch Window 2
4724 touchedPoint = {150, 150};
4725 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004726 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4727 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004728
chaviw9eaa22c2020-07-01 16:21:27 -07004729 // Update the transform so rotation is set
4730 mWindow2->setWindowTransform(0, -1, 1, 0);
4731 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4732 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004733}
4734
chaviw9eaa22c2020-07-01 16:21:27 -07004735TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004736 mWindow2->setWindowScale(0.5f, 0.5f);
4737
4738 // Touch Window 1
4739 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4740 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004741 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004742
4743 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004744 touchedPoints.push_back(PointF{150, 150});
4745 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004746 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004747
chaviw9eaa22c2020-07-01 16:21:27 -07004748 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004749 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004750 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004751
chaviw9eaa22c2020-07-01 16:21:27 -07004752 // Update the transform so rotation is set for Window 2
4753 mWindow2->setWindowTransform(0, -1, 1, 0);
4754 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004755 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004756}
4757
chaviw9eaa22c2020-07-01 16:21:27 -07004758TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004759 mWindow2->setWindowScale(0.5f, 0.5f);
4760
4761 // Touch Window 1
4762 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4763 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004764 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004765
4766 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004767 touchedPoints.push_back(PointF{150, 150});
4768 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004769
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004770 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004771
4772 // Move both windows
4773 touchedPoints = {{20, 20}, {175, 175}};
4774 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4775 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4776
chaviw9eaa22c2020-07-01 16:21:27 -07004777 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004778
chaviw9eaa22c2020-07-01 16:21:27 -07004779 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004780 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004781 expectedPoints.pop_back();
4782
4783 // Touch Window 2
4784 mWindow2->setWindowTransform(0, -1, 1, 0);
4785 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004786 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004787
4788 // Move both windows
4789 touchedPoints = {{20, 20}, {175, 175}};
4790 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4791 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4792
4793 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004794}
4795
4796TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4797 mWindow1->setWindowScale(0.5f, 0.5f);
4798
4799 // Touch Window 1
4800 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4801 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004802 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004803
4804 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004805 touchedPoints.push_back(PointF{150, 150});
4806 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004807
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004808 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004809
4810 // Move both windows
4811 touchedPoints = {{20, 20}, {175, 175}};
4812 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4813 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4814
chaviw9eaa22c2020-07-01 16:21:27 -07004815 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004816}
4817
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004818class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4819 virtual void SetUp() override {
4820 InputDispatcherTest::SetUp();
4821
Chris Yea209fde2020-07-22 13:54:51 -07004822 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004823 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004824 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4825 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004826 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004827 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004828 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004829
4830 // Set focused application.
4831 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4832
4833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004834 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004835 mWindow->consumeFocusEvent(true);
4836 }
4837
4838 virtual void TearDown() override {
4839 InputDispatcherTest::TearDown();
4840 mWindow.clear();
4841 }
4842
4843protected:
Chris Yea209fde2020-07-22 13:54:51 -07004844 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004845 sp<FakeWindowHandle> mWindow;
4846 static constexpr PointF WINDOW_LOCATION = {20, 20};
4847
4848 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4851 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004853 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4854 WINDOW_LOCATION));
4855 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004856
4857 sp<FakeWindowHandle> addSpyWindow() {
4858 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004859 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004860 spy->setTrustedOverlay(true);
4861 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004862 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004863 spy->setDispatchingTimeout(30ms);
4864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4865 return spy;
4866 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004867};
4868
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004869// Send a tap and respond, which should not cause an ANR.
4870TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4871 tapOnWindow();
4872 mWindow->consumeMotionDown();
4873 mWindow->consumeMotionUp();
4874 ASSERT_TRUE(mDispatcher->waitForIdle());
4875 mFakePolicy->assertNotifyAnrWasNotCalled();
4876}
4877
4878// Send a regular key and respond, which should not cause an ANR.
4879TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4882 ASSERT_TRUE(mDispatcher->waitForIdle());
4883 mFakePolicy->assertNotifyAnrWasNotCalled();
4884}
4885
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004886TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4887 mWindow->setFocusable(false);
4888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4889 mWindow->consumeFocusEvent(false);
4890
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004891 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004892 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004893 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4894 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004896 // Key will not go to window because we have no focused window.
4897 // The 'no focused window' ANR timer should start instead.
4898
4899 // Now, the focused application goes away.
4900 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4901 // The key should get dropped and there should be no ANR.
4902
4903 ASSERT_TRUE(mDispatcher->waitForIdle());
4904 mFakePolicy->assertNotifyAnrWasNotCalled();
4905}
4906
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004907// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004908// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4909// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004910TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004912 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4913 WINDOW_LOCATION));
4914
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004915 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4916 ASSERT_TRUE(sequenceNum);
4917 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004918 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920 mWindow->finishEvent(*sequenceNum);
4921 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4922 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004923 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004924 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004925}
4926
4927// Send a key to the app and have the app not respond right away.
4928TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4929 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004931 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4932 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004933 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004934 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004935 ASSERT_TRUE(mDispatcher->waitForIdle());
4936}
4937
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004938// We have a focused application, but no focused window
4939TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004940 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4942 mWindow->consumeFocusEvent(false);
4943
4944 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4947 WINDOW_LOCATION));
4948 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4949 mDispatcher->waitForIdle();
4950 mFakePolicy->assertNotifyAnrWasNotCalled();
4951
4952 // Once a focused event arrives, we get an ANR for this application
4953 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4954 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004957 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004958 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07004960 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004961 ASSERT_TRUE(mDispatcher->waitForIdle());
4962}
4963
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004964/**
4965 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4966 * there will not be an ANR.
4967 */
4968TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4969 mWindow->setFocusable(false);
4970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4971 mWindow->consumeFocusEvent(false);
4972
4973 KeyEvent event;
4974 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4975 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4976
4977 // Define a valid key down event that is stale (too old).
4978 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4979 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4980 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4981
4982 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4983
4984 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004985 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004986 InputEventInjectionSync::WAIT_FOR_RESULT,
4987 INJECT_EVENT_TIMEOUT, policyFlags);
4988 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4989 << "Injection should fail because the event is stale";
4990
4991 ASSERT_TRUE(mDispatcher->waitForIdle());
4992 mFakePolicy->assertNotifyAnrWasNotCalled();
4993 mWindow->assertNoEvents();
4994}
4995
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004997// Make sure that we don't notify policy twice about the same ANR.
4998TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004999 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5001 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002
5003 // Once a focused event arrives, we get an ANR for this application
5004 // We specify the injection timeout to be smaller than the application timeout, to ensure that
5005 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005006 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005007 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005008 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005009 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07005010 const std::chrono::duration appTimeout =
5011 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5012 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005013
Vishnu Naire4df8752022-09-08 09:17:55 -07005014 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005015 // ANR should not be raised again. It is up to policy to do that if it desires.
5016 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005017
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005018 // If we now get a focused window, the ANR should stop, but the policy handles that via
5019 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020 ASSERT_TRUE(mDispatcher->waitForIdle());
5021}
5022
5023// We have a focused application, but no focused window
5024TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005025 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5027 mWindow->consumeFocusEvent(false);
5028
5029 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005030 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005032 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5033 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005034
Vishnu Naire4df8752022-09-08 09:17:55 -07005035 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
5036 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037
5038 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005039 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005040 ASSERT_TRUE(mDispatcher->waitForIdle());
5041 mWindow->assertNoEvents();
5042}
5043
5044/**
5045 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5046 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5047 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5048 * the ANR mechanism should still work.
5049 *
5050 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5051 * DOWN event, while not responding on the second one.
5052 */
5053TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5054 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5055 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5056 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5057 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5058 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005059 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005060
5061 // Now send ACTION_UP, with identical timestamp
5062 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5063 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5064 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5065 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005066 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067
5068 // We have now sent down and up. Let's consume first event and then ANR on the second.
5069 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5070 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005071 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005072}
5073
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005074// A spy window can receive an ANR
5075TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5076 sp<FakeWindowHandle> spy = addSpyWindow();
5077
5078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5079 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5080 WINDOW_LOCATION));
5081 mWindow->consumeMotionDown();
5082
5083 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5084 ASSERT_TRUE(sequenceNum);
5085 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005086 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005087
5088 spy->finishEvent(*sequenceNum);
5089 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
5090 0 /*flags*/);
5091 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005092 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005093}
5094
5095// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005097TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5098 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5101 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005104
5105 // Stuck on the ACTION_UP
5106 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005107 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005108
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005109 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005111 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5112 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113
5114 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5115 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005116 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005117 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005118 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005119}
5120
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005121// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005122// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005123TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5124 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005125
5126 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005127 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5128 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005129
5130 mWindow->consumeMotionDown();
5131 // Stuck on the ACTION_UP
5132 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005133 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005134
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005135 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005137 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5138 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005139
5140 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5141 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005142 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005143 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005144 spy->assertNoEvents();
5145}
5146
5147TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5148 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5149
5150 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5151
5152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5153 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5154 WINDOW_LOCATION));
5155
5156 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5157 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5158 ASSERT_TRUE(consumeSeq);
5159
Prabir Pradhanedd96402022-02-15 01:46:16 -08005160 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005161
5162 monitor.finishEvent(*consumeSeq);
5163 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5164
5165 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005166 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005167}
5168
5169// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5170// process events, you don't get an anr. When the window later becomes unresponsive again, you
5171// get an ANR again.
5172// 1. tap -> block on ACTION_UP -> receive ANR
5173// 2. consume all pending events (= queue becomes healthy again)
5174// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5175TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5176 tapOnWindow();
5177
5178 mWindow->consumeMotionDown();
5179 // Block on ACTION_UP
5180 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005181 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005182 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5183 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005184 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005185 mWindow->assertNoEvents();
5186
5187 tapOnWindow();
5188 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005189 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005190 mWindow->consumeMotionUp();
5191
5192 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005193 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005194 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005195 mWindow->assertNoEvents();
5196}
5197
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005198// If a connection remains unresponsive for a while, make sure policy is only notified once about
5199// it.
5200TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005201 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5203 WINDOW_LOCATION));
5204
5205 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005206 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005207 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005208 // 'notifyConnectionUnresponsive' should only be called once per connection
5209 mFakePolicy->assertNotifyAnrWasNotCalled();
5210 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 mWindow->consumeMotionDown();
5212 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5213 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5214 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005215 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005216 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005217 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005218}
5219
5220/**
5221 * If a window is processing a motion event, and then a key event comes in, the key event should
5222 * not to to the focused window until the motion is processed.
5223 *
5224 * Warning!!!
5225 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5226 * and the injection timeout that we specify when injecting the key.
5227 * We must have the injection timeout (10ms) be smaller than
5228 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5229 *
5230 * If that value changes, this test should also change.
5231 */
5232TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5233 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5235
5236 tapOnWindow();
5237 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5238 ASSERT_TRUE(downSequenceNum);
5239 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5240 ASSERT_TRUE(upSequenceNum);
5241 // Don't finish the events yet, and send a key
5242 // Injection will "succeed" because we will eventually give up and send the key to the focused
5243 // window even if motions are still being processed. But because the injection timeout is short,
5244 // we will receive INJECTION_TIMED_OUT as the result.
5245
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005246 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005247 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005248 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5249 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005250 // Key will not be sent to the window, yet, because the window is still processing events
5251 // and the key remains pending, waiting for the touch events to be processed
5252 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5253 ASSERT_FALSE(keySequenceNum);
5254
5255 std::this_thread::sleep_for(500ms);
5256 // if we wait long enough though, dispatcher will give up, and still send the key
5257 // to the focused window, even though we have not yet finished the motion event
5258 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5259 mWindow->finishEvent(*downSequenceNum);
5260 mWindow->finishEvent(*upSequenceNum);
5261}
5262
5263/**
5264 * If a window is processing a motion event, and then a key event comes in, the key event should
5265 * not go to the focused window until the motion is processed.
5266 * If then a new motion comes in, then the pending key event should be going to the currently
5267 * focused window right away.
5268 */
5269TEST_F(InputDispatcherSingleWindowAnr,
5270 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5271 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5272 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5273
5274 tapOnWindow();
5275 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5276 ASSERT_TRUE(downSequenceNum);
5277 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5278 ASSERT_TRUE(upSequenceNum);
5279 // Don't finish the events yet, and send a key
5280 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005282 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005283 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005284 // At this point, key is still pending, and should not be sent to the application yet.
5285 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5286 ASSERT_FALSE(keySequenceNum);
5287
5288 // Now tap down again. It should cause the pending key to go to the focused window right away.
5289 tapOnWindow();
5290 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5291 // the other events yet. We can finish events in any order.
5292 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5293 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5294 mWindow->consumeMotionDown();
5295 mWindow->consumeMotionUp();
5296 mWindow->assertNoEvents();
5297}
5298
5299class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5300 virtual void SetUp() override {
5301 InputDispatcherTest::SetUp();
5302
Chris Yea209fde2020-07-22 13:54:51 -07005303 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005304 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005305 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5306 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005307 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005308 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005309 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005310
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005311 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5312 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005313 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005314 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005315
5316 // Set focused application.
5317 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005318 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005319
5320 // Expect one focus window exist in display.
5321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005322 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323 mFocusedWindow->consumeFocusEvent(true);
5324 }
5325
5326 virtual void TearDown() override {
5327 InputDispatcherTest::TearDown();
5328
5329 mUnfocusedWindow.clear();
5330 mFocusedWindow.clear();
5331 }
5332
5333protected:
Chris Yea209fde2020-07-22 13:54:51 -07005334 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005335 sp<FakeWindowHandle> mUnfocusedWindow;
5336 sp<FakeWindowHandle> mFocusedWindow;
5337 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5338 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5339 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5340
5341 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5342
5343 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5344
5345private:
5346 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005348 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5349 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005351 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5352 location));
5353 }
5354};
5355
5356// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5357// should be ANR'd first.
5358TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005360 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5361 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005362 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005363 mFocusedWindow->consumeMotionDown();
5364 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5365 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5366 // We consumed all events, so no ANR
5367 ASSERT_TRUE(mDispatcher->waitForIdle());
5368 mFakePolicy->assertNotifyAnrWasNotCalled();
5369
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005370 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005371 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5372 FOCUSED_WINDOW_LOCATION));
5373 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5374 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005375
5376 const std::chrono::duration timeout =
5377 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005378 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005379 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5380 // sequence to make it consistent
5381 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005382 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005383 mFocusedWindow->consumeMotionDown();
5384 // This cancel is generated because the connection was unresponsive
5385 mFocusedWindow->consumeMotionCancel();
5386 mFocusedWindow->assertNoEvents();
5387 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005388 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005389 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5390 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005391 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005392}
5393
5394// If we have 2 windows with identical timeouts that are both unresponsive,
5395// it doesn't matter which order they should have ANR.
5396// But we should receive ANR for both.
5397TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5398 // Set the timeout for unfocused window to match the focused window
5399 mUnfocusedWindow->setDispatchingTimeout(10ms);
5400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5401
5402 tapOnFocusedWindow();
5403 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005404 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5405 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5406 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005407
5408 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005409 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5410 mFocusedWindow->getToken() == anrConnectionToken2);
5411 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5412 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005413
5414 ASSERT_TRUE(mDispatcher->waitForIdle());
5415 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005416
5417 mFocusedWindow->consumeMotionDown();
5418 mFocusedWindow->consumeMotionUp();
5419 mUnfocusedWindow->consumeMotionOutside();
5420
Prabir Pradhanedd96402022-02-15 01:46:16 -08005421 sp<IBinder> responsiveToken1, responsiveToken2;
5422 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5423 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005424
5425 // Both applications should be marked as responsive, in any order
5426 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5427 mFocusedWindow->getToken() == responsiveToken2);
5428 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5429 mUnfocusedWindow->getToken() == responsiveToken2);
5430 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005431}
5432
5433// If a window is already not responding, the second tap on the same window should be ignored.
5434// We should also log an error to account for the dropped event (not tested here).
5435// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5436TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5437 tapOnFocusedWindow();
5438 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5439 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5440 // Receive the events, but don't respond
5441 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5442 ASSERT_TRUE(downEventSequenceNum);
5443 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5444 ASSERT_TRUE(upEventSequenceNum);
5445 const std::chrono::duration timeout =
5446 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005447 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005448
5449 // Tap once again
5450 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005451 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005452 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5453 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005454 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005455 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5456 FOCUSED_WINDOW_LOCATION));
5457 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5458 // valid touch target
5459 mUnfocusedWindow->assertNoEvents();
5460
5461 // Consume the first tap
5462 mFocusedWindow->finishEvent(*downEventSequenceNum);
5463 mFocusedWindow->finishEvent(*upEventSequenceNum);
5464 ASSERT_TRUE(mDispatcher->waitForIdle());
5465 // The second tap did not go to the focused window
5466 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005467 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005468 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5469 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005470 mFakePolicy->assertNotifyAnrWasNotCalled();
5471}
5472
5473// If you tap outside of all windows, there will not be ANR
5474TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005475 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005476 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5477 LOCATION_OUTSIDE_ALL_WINDOWS));
5478 ASSERT_TRUE(mDispatcher->waitForIdle());
5479 mFakePolicy->assertNotifyAnrWasNotCalled();
5480}
5481
5482// Since the focused window is paused, tapping on it should not produce any events
5483TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5484 mFocusedWindow->setPaused(true);
5485 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5486
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005487 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5489 FOCUSED_WINDOW_LOCATION));
5490
5491 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5492 ASSERT_TRUE(mDispatcher->waitForIdle());
5493 // Should not ANR because the window is paused, and touches shouldn't go to it
5494 mFakePolicy->assertNotifyAnrWasNotCalled();
5495
5496 mFocusedWindow->assertNoEvents();
5497 mUnfocusedWindow->assertNoEvents();
5498}
5499
5500/**
5501 * If a window is processing a motion event, and then a key event comes in, the key event should
5502 * not to to the focused window until the motion is processed.
5503 * If a different window becomes focused at this time, the key should go to that window instead.
5504 *
5505 * Warning!!!
5506 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5507 * and the injection timeout that we specify when injecting the key.
5508 * We must have the injection timeout (10ms) be smaller than
5509 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5510 *
5511 * If that value changes, this test should also change.
5512 */
5513TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5514 // Set a long ANR timeout to prevent it from triggering
5515 mFocusedWindow->setDispatchingTimeout(2s);
5516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5517
5518 tapOnUnfocusedWindow();
5519 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5520 ASSERT_TRUE(downSequenceNum);
5521 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5522 ASSERT_TRUE(upSequenceNum);
5523 // Don't finish the events yet, and send a key
5524 // Injection will succeed because we will eventually give up and send the key to the focused
5525 // window even if motions are still being processed.
5526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005527 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005529 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005531 // Key will not be sent to the window, yet, because the window is still processing events
5532 // and the key remains pending, waiting for the touch events to be processed
5533 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5534 ASSERT_FALSE(keySequenceNum);
5535
5536 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005537 mFocusedWindow->setFocusable(false);
5538 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005540 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005541
5542 // Focus events should precede the key events
5543 mUnfocusedWindow->consumeFocusEvent(true);
5544 mFocusedWindow->consumeFocusEvent(false);
5545
5546 // Finish the tap events, which should unblock dispatcher
5547 mUnfocusedWindow->finishEvent(*downSequenceNum);
5548 mUnfocusedWindow->finishEvent(*upSequenceNum);
5549
5550 // Now that all queues are cleared and no backlog in the connections, the key event
5551 // can finally go to the newly focused "mUnfocusedWindow".
5552 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5553 mFocusedWindow->assertNoEvents();
5554 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005555 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005556}
5557
5558// When the touch stream is split across 2 windows, and one of them does not respond,
5559// then ANR should be raised and the touch should be canceled for the unresponsive window.
5560// The other window should not be affected by that.
5561TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5562 // Touch Window 1
5563 NotifyMotionArgs motionArgs =
5564 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5565 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5566 mDispatcher->notifyMotion(&motionArgs);
5567 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5568 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5569
5570 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005571 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5572 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005573 mDispatcher->notifyMotion(&motionArgs);
5574
5575 const std::chrono::duration timeout =
5576 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005577 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005578
5579 mUnfocusedWindow->consumeMotionDown();
5580 mFocusedWindow->consumeMotionDown();
5581 // Focused window may or may not receive ACTION_MOVE
5582 // But it should definitely receive ACTION_CANCEL due to the ANR
5583 InputEvent* event;
5584 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5585 ASSERT_TRUE(moveOrCancelSequenceNum);
5586 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5587 ASSERT_NE(nullptr, event);
5588 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5589 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5590 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5591 mFocusedWindow->consumeMotionCancel();
5592 } else {
5593 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5594 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005595 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005596 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5597 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005598
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005599 mUnfocusedWindow->assertNoEvents();
5600 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005601 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005602}
5603
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005604/**
5605 * If we have no focused window, and a key comes in, we start the ANR timer.
5606 * The focused application should add a focused window before the timer runs out to prevent ANR.
5607 *
5608 * If the user touches another application during this time, the key should be dropped.
5609 * Next, if a new focused window comes in, without toggling the focused application,
5610 * then no ANR should occur.
5611 *
5612 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5613 * but in some cases the policy may not update the focused application.
5614 */
5615TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5616 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5617 std::make_shared<FakeApplicationHandle>();
5618 focusedApplication->setDispatchingTimeout(60ms);
5619 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5620 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5621 mFocusedWindow->setFocusable(false);
5622
5623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5624 mFocusedWindow->consumeFocusEvent(false);
5625
5626 // Send a key. The ANR timer should start because there is no focused window.
5627 // 'focusedApplication' will get blamed if this timer completes.
5628 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005629 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005630 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005631 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5632 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005634
5635 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5636 // then the injected touches won't cause the focused event to get dropped.
5637 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5638 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5639 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5640 // For this test, it means that the key would get delivered to the window once it becomes
5641 // focused.
5642 std::this_thread::sleep_for(10ms);
5643
5644 // Touch unfocused window. This should force the pending key to get dropped.
5645 NotifyMotionArgs motionArgs =
5646 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5647 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5648 mDispatcher->notifyMotion(&motionArgs);
5649
5650 // We do not consume the motion right away, because that would require dispatcher to first
5651 // process (== drop) the key event, and by that time, ANR will be raised.
5652 // Set the focused window first.
5653 mFocusedWindow->setFocusable(true);
5654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5655 setFocusedWindow(mFocusedWindow);
5656 mFocusedWindow->consumeFocusEvent(true);
5657 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5658 // to another application. This could be a bug / behaviour in the policy.
5659
5660 mUnfocusedWindow->consumeMotionDown();
5661
5662 ASSERT_TRUE(mDispatcher->waitForIdle());
5663 // Should not ANR because we actually have a focused window. It was just added too slowly.
5664 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5665}
5666
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005667// These tests ensure we cannot send touch events to a window that's positioned behind a window
5668// that has feature NO_INPUT_CHANNEL.
5669// Layout:
5670// Top (closest to user)
5671// mNoInputWindow (above all windows)
5672// mBottomWindow
5673// Bottom (furthest from user)
5674class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5675 virtual void SetUp() override {
5676 InputDispatcherTest::SetUp();
5677
5678 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005679 mNoInputWindow =
5680 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5681 "Window without input channel", ADISPLAY_ID_DEFAULT,
5682 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005683 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005684 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5685 // It's perfectly valid for this window to not have an associated input channel
5686
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005687 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5688 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005689 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5690
5691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5692 }
5693
5694protected:
5695 std::shared_ptr<FakeApplicationHandle> mApplication;
5696 sp<FakeWindowHandle> mNoInputWindow;
5697 sp<FakeWindowHandle> mBottomWindow;
5698};
5699
5700TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5701 PointF touchedPoint = {10, 10};
5702
5703 NotifyMotionArgs motionArgs =
5704 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5705 ADISPLAY_ID_DEFAULT, {touchedPoint});
5706 mDispatcher->notifyMotion(&motionArgs);
5707
5708 mNoInputWindow->assertNoEvents();
5709 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5710 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5711 // and therefore should prevent mBottomWindow from receiving touches
5712 mBottomWindow->assertNoEvents();
5713}
5714
5715/**
5716 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5717 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5718 */
5719TEST_F(InputDispatcherMultiWindowOcclusionTests,
5720 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005721 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5722 "Window with input channel and NO_INPUT_CHANNEL",
5723 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005724
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005725 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005726 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5728
5729 PointF touchedPoint = {10, 10};
5730
5731 NotifyMotionArgs motionArgs =
5732 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5733 ADISPLAY_ID_DEFAULT, {touchedPoint});
5734 mDispatcher->notifyMotion(&motionArgs);
5735
5736 mNoInputWindow->assertNoEvents();
5737 mBottomWindow->assertNoEvents();
5738}
5739
Vishnu Nair958da932020-08-21 17:12:37 -07005740class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5741protected:
5742 std::shared_ptr<FakeApplicationHandle> mApp;
5743 sp<FakeWindowHandle> mWindow;
5744 sp<FakeWindowHandle> mMirror;
5745
5746 virtual void SetUp() override {
5747 InputDispatcherTest::SetUp();
5748 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005749 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5750 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5751 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005752 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5753 mWindow->setFocusable(true);
5754 mMirror->setFocusable(true);
5755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5756 }
5757};
5758
5759TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5760 // Request focus on a mirrored window
5761 setFocusedWindow(mMirror);
5762
5763 // window gets focused
5764 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5766 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005767 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5768}
5769
5770// A focused & mirrored window remains focused only if the window and its mirror are both
5771// focusable.
5772TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5773 setFocusedWindow(mMirror);
5774
5775 // window gets focused
5776 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5778 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005779 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5781 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005782 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5783
5784 mMirror->setFocusable(false);
5785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5786
5787 // window loses focus since one of the windows associated with the token in not focusable
5788 mWindow->consumeFocusEvent(false);
5789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005790 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5791 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005792 mWindow->assertNoEvents();
5793}
5794
5795// A focused & mirrored window remains focused until the window and its mirror both become
5796// invisible.
5797TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5798 setFocusedWindow(mMirror);
5799
5800 // window gets focused
5801 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5803 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005804 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5806 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005807 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5808
5809 mMirror->setVisible(false);
5810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5813 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005814 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5816 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005817 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5818
5819 mWindow->setVisible(false);
5820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5821
5822 // window loses focus only after all windows associated with the token become invisible.
5823 mWindow->consumeFocusEvent(false);
5824
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005825 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5826 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005827 mWindow->assertNoEvents();
5828}
5829
5830// A focused & mirrored window remains focused until both windows are removed.
5831TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5832 setFocusedWindow(mMirror);
5833
5834 // window gets focused
5835 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5837 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005838 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5840 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005841 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5842
5843 // single window is removed but the window token remains focused
5844 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5845
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5847 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005848 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5850 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005851 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5852
5853 // Both windows are removed
5854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5855 mWindow->consumeFocusEvent(false);
5856
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005857 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5858 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005859 mWindow->assertNoEvents();
5860}
5861
5862// Focus request can be pending until one window becomes visible.
5863TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5864 // Request focus on an invisible mirror.
5865 mWindow->setVisible(false);
5866 mMirror->setVisible(false);
5867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5868 setFocusedWindow(mMirror);
5869
5870 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005872 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005873 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005874
5875 mMirror->setVisible(true);
5876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5877
5878 // window gets focused
5879 mWindow->consumeFocusEvent(true);
5880 // window gets the pending key event
5881 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5882}
Prabir Pradhan99987712020-11-10 18:43:05 -08005883
5884class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5885protected:
5886 std::shared_ptr<FakeApplicationHandle> mApp;
5887 sp<FakeWindowHandle> mWindow;
5888 sp<FakeWindowHandle> mSecondWindow;
5889
5890 void SetUp() override {
5891 InputDispatcherTest::SetUp();
5892 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005893 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005894 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005895 mSecondWindow =
5896 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005897 mSecondWindow->setFocusable(true);
5898
5899 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5901
5902 setFocusedWindow(mWindow);
5903 mWindow->consumeFocusEvent(true);
5904 }
5905
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005906 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5907 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005908 mDispatcher->notifyPointerCaptureChanged(&args);
5909 }
5910
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005911 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5912 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005913 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005914 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5915 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005916 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005917 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005918 }
5919};
5920
5921TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5922 // Ensure that capture cannot be obtained for unfocused windows.
5923 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5924 mFakePolicy->assertSetPointerCaptureNotCalled();
5925 mSecondWindow->assertNoEvents();
5926
5927 // Ensure that capture can be enabled from the focus window.
5928 requestAndVerifyPointerCapture(mWindow, true);
5929
5930 // Ensure that capture cannot be disabled from a window that does not have capture.
5931 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5932 mFakePolicy->assertSetPointerCaptureNotCalled();
5933
5934 // Ensure that capture can be disabled from the window with capture.
5935 requestAndVerifyPointerCapture(mWindow, false);
5936}
5937
5938TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005939 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005940
5941 setFocusedWindow(mSecondWindow);
5942
5943 // Ensure that the capture disabled event was sent first.
5944 mWindow->consumeCaptureEvent(false);
5945 mWindow->consumeFocusEvent(false);
5946 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005947 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005948
5949 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005950 notifyPointerCaptureChanged({});
5951 notifyPointerCaptureChanged(request);
5952 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005953 mWindow->assertNoEvents();
5954 mSecondWindow->assertNoEvents();
5955 mFakePolicy->assertSetPointerCaptureNotCalled();
5956}
5957
5958TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005959 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005960
5961 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005962 notifyPointerCaptureChanged({});
5963 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005964
5965 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005966 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005967 mWindow->consumeCaptureEvent(false);
5968 mWindow->assertNoEvents();
5969}
5970
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005971TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5972 requestAndVerifyPointerCapture(mWindow, true);
5973
5974 // The first window loses focus.
5975 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005976 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005977 mWindow->consumeCaptureEvent(false);
5978
5979 // Request Pointer Capture from the second window before the notification from InputReader
5980 // arrives.
5981 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005982 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005983
5984 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005985 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005986
5987 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005988 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005989
5990 mSecondWindow->consumeFocusEvent(true);
5991 mSecondWindow->consumeCaptureEvent(true);
5992}
5993
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005994TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5995 // App repeatedly enables and disables capture.
5996 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5997 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5998 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5999 mFakePolicy->assertSetPointerCaptureCalled(false);
6000 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6001 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6002
6003 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
6004 // first request is now stale, this should do nothing.
6005 notifyPointerCaptureChanged(firstRequest);
6006 mWindow->assertNoEvents();
6007
6008 // InputReader notifies that the second request was enabled.
6009 notifyPointerCaptureChanged(secondRequest);
6010 mWindow->consumeCaptureEvent(true);
6011}
6012
Prabir Pradhan7092e262022-05-03 16:51:09 +00006013TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6014 requestAndVerifyPointerCapture(mWindow, true);
6015
6016 // App toggles pointer capture off and on.
6017 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6018 mFakePolicy->assertSetPointerCaptureCalled(false);
6019
6020 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6021 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6022
6023 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6024 // preceding "disable" request.
6025 notifyPointerCaptureChanged(enableRequest);
6026
6027 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6028 // any notifications.
6029 mWindow->assertNoEvents();
6030}
6031
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006032class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6033protected:
6034 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006035
6036 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6037 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6038
6039 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6040 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6041
6042 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6043 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6044 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6045 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6046 MAXIMUM_OBSCURING_OPACITY);
6047
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006048 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006049 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006050 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006051
6052 sp<FakeWindowHandle> mTouchWindow;
6053
6054 virtual void SetUp() override {
6055 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006056 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006057 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6058 }
6059
6060 virtual void TearDown() override {
6061 InputDispatcherTest::TearDown();
6062 mTouchWindow.clear();
6063 }
6064
chaviw3277faf2021-05-19 16:45:23 -05006065 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6066 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006067 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006068 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006069 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006070 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006071 return window;
6072 }
6073
6074 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6075 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6076 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006077 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006078 // Generate an arbitrary PID based on the UID
6079 window->setOwnerInfo(1777 + (uid % 10000), uid);
6080 return window;
6081 }
6082
6083 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6084 NotifyMotionArgs args =
6085 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6086 ADISPLAY_ID_DEFAULT, points);
6087 mDispatcher->notifyMotion(&args);
6088 }
6089};
6090
6091TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006092 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006093 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006095
6096 touch();
6097
6098 mTouchWindow->assertNoEvents();
6099}
6100
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006101TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006102 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6103 const sp<FakeWindowHandle>& w =
6104 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6106
6107 touch();
6108
6109 mTouchWindow->assertNoEvents();
6110}
6111
6112TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006113 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6114 const sp<FakeWindowHandle>& w =
6115 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6117
6118 touch();
6119
6120 w->assertNoEvents();
6121}
6122
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006123TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006124 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006126
6127 touch();
6128
6129 mTouchWindow->consumeAnyMotionDown();
6130}
6131
6132TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006133 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006134 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006135 w->setFrame(Rect(0, 0, 50, 50));
6136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006137
6138 touch({PointF{100, 100}});
6139
6140 mTouchWindow->consumeAnyMotionDown();
6141}
6142
6143TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006144 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006145 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6147
6148 touch();
6149
6150 mTouchWindow->consumeAnyMotionDown();
6151}
6152
6153TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6154 const sp<FakeWindowHandle>& w =
6155 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006157
6158 touch();
6159
6160 mTouchWindow->consumeAnyMotionDown();
6161}
6162
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006163TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6164 const sp<FakeWindowHandle>& w =
6165 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6166 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6167
6168 touch();
6169
6170 w->assertNoEvents();
6171}
6172
6173/**
6174 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6175 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6176 * window, the occluding window will still receive ACTION_OUTSIDE event.
6177 */
6178TEST_F(InputDispatcherUntrustedTouchesTest,
6179 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6180 const sp<FakeWindowHandle>& w =
6181 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006182 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6184
6185 touch();
6186
6187 w->consumeMotionOutside();
6188}
6189
6190TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6191 const sp<FakeWindowHandle>& w =
6192 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006193 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6195
6196 touch();
6197
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006198 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006199}
6200
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006201TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006202 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006203 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6204 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6206
6207 touch();
6208
6209 mTouchWindow->consumeAnyMotionDown();
6210}
6211
6212TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6213 const sp<FakeWindowHandle>& w =
6214 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6215 MAXIMUM_OBSCURING_OPACITY);
6216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006217
6218 touch();
6219
6220 mTouchWindow->consumeAnyMotionDown();
6221}
6222
6223TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006224 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006225 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6226 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6228
6229 touch();
6230
6231 mTouchWindow->assertNoEvents();
6232}
6233
6234TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6235 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6236 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006237 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6238 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006239 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006240 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6241 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006242 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6243
6244 touch();
6245
6246 mTouchWindow->assertNoEvents();
6247}
6248
6249TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6250 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6251 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006252 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6253 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006254 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006255 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6256 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6258
6259 touch();
6260
6261 mTouchWindow->consumeAnyMotionDown();
6262}
6263
6264TEST_F(InputDispatcherUntrustedTouchesTest,
6265 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6266 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006267 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6268 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006269 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006270 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6271 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006272 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6273
6274 touch();
6275
6276 mTouchWindow->consumeAnyMotionDown();
6277}
6278
6279TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6280 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006281 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6282 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006283 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006284 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6285 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006287
6288 touch();
6289
6290 mTouchWindow->assertNoEvents();
6291}
6292
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006293TEST_F(InputDispatcherUntrustedTouchesTest,
6294 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6295 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006296 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6297 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006298 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006299 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6300 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6302
6303 touch();
6304
6305 mTouchWindow->assertNoEvents();
6306}
6307
6308TEST_F(InputDispatcherUntrustedTouchesTest,
6309 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6310 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006311 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6312 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006313 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006314 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6315 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6317
6318 touch();
6319
6320 mTouchWindow->consumeAnyMotionDown();
6321}
6322
6323TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6324 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006325 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6326 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6328
6329 touch();
6330
6331 mTouchWindow->consumeAnyMotionDown();
6332}
6333
6334TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6335 const sp<FakeWindowHandle>& w =
6336 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6338
6339 touch();
6340
6341 mTouchWindow->consumeAnyMotionDown();
6342}
6343
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006344TEST_F(InputDispatcherUntrustedTouchesTest,
6345 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6346 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6347 const sp<FakeWindowHandle>& w =
6348 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6350
6351 touch();
6352
6353 mTouchWindow->assertNoEvents();
6354}
6355
6356TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6357 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6358 const sp<FakeWindowHandle>& w =
6359 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6361
6362 touch();
6363
6364 mTouchWindow->consumeAnyMotionDown();
6365}
6366
6367TEST_F(InputDispatcherUntrustedTouchesTest,
6368 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6369 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6370 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006371 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6372 OPACITY_ABOVE_THRESHOLD);
6373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6374
6375 touch();
6376
6377 mTouchWindow->consumeAnyMotionDown();
6378}
6379
6380TEST_F(InputDispatcherUntrustedTouchesTest,
6381 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6382 const sp<FakeWindowHandle>& w1 =
6383 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6384 OPACITY_BELOW_THRESHOLD);
6385 const sp<FakeWindowHandle>& w2 =
6386 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6387 OPACITY_BELOW_THRESHOLD);
6388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6389
6390 touch();
6391
6392 mTouchWindow->assertNoEvents();
6393}
6394
6395/**
6396 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6397 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6398 * (which alone would result in allowing touches) does not affect the blocking behavior.
6399 */
6400TEST_F(InputDispatcherUntrustedTouchesTest,
6401 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6402 const sp<FakeWindowHandle>& wB =
6403 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6404 OPACITY_BELOW_THRESHOLD);
6405 const sp<FakeWindowHandle>& wC =
6406 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6407 OPACITY_BELOW_THRESHOLD);
6408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6409
6410 touch();
6411
6412 mTouchWindow->assertNoEvents();
6413}
6414
6415/**
6416 * This test is testing that a window from a different UID but with same application token doesn't
6417 * block the touch. Apps can share the application token for close UI collaboration for example.
6418 */
6419TEST_F(InputDispatcherUntrustedTouchesTest,
6420 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6421 const sp<FakeWindowHandle>& w =
6422 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6423 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6425
6426 touch();
6427
6428 mTouchWindow->consumeAnyMotionDown();
6429}
6430
arthurhungb89ccb02020-12-30 16:19:01 +08006431class InputDispatcherDragTests : public InputDispatcherTest {
6432protected:
6433 std::shared_ptr<FakeApplicationHandle> mApp;
6434 sp<FakeWindowHandle> mWindow;
6435 sp<FakeWindowHandle> mSecondWindow;
6436 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006437 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006438 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6439 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006440
6441 void SetUp() override {
6442 InputDispatcherTest::SetUp();
6443 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006444 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006445 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006446
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006447 mSecondWindow =
6448 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006449 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006450
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006451 mSpyWindow =
6452 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006453 mSpyWindow->setSpy(true);
6454 mSpyWindow->setTrustedOverlay(true);
6455 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6456
arthurhungb89ccb02020-12-30 16:19:01 +08006457 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006459 }
6460
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006461 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6462 switch (fromSource) {
6463 case AINPUT_SOURCE_TOUCHSCREEN:
6464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6465 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6466 ADISPLAY_ID_DEFAULT, {50, 50}))
6467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6468 break;
6469 case AINPUT_SOURCE_STYLUS:
6470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6471 injectMotionEvent(
6472 mDispatcher,
6473 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6474 AINPUT_SOURCE_STYLUS)
6475 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6476 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6477 .x(50)
6478 .y(50))
6479 .build()));
6480 break;
6481 case AINPUT_SOURCE_MOUSE:
6482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6483 injectMotionEvent(
6484 mDispatcher,
6485 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6486 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6487 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6488 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6489 .x(50)
6490 .y(50))
6491 .build()));
6492 break;
6493 default:
6494 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6495 }
arthurhungb89ccb02020-12-30 16:19:01 +08006496
6497 // Window should receive motion event.
6498 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006499 // Spy window should also receive motion event
6500 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006501 }
6502
6503 // Start performing drag, we will create a drag window and transfer touch to it.
6504 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6505 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006506 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006507 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006508 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006509 }
arthurhungb89ccb02020-12-30 16:19:01 +08006510
6511 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006512 mDragWindow =
6513 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006514 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006515 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006516 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006517
6518 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006519 bool transferred =
6520 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6521 true /* isDragDrop */);
6522 if (transferred) {
6523 mWindow->consumeMotionCancel();
6524 mDragWindow->consumeMotionDown();
6525 }
6526 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006527 }
6528};
6529
6530TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006531 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006532
6533 // Move on window.
6534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6535 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6536 ADISPLAY_ID_DEFAULT, {50, 50}))
6537 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6538 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6539 mWindow->consumeDragEvent(false, 50, 50);
6540 mSecondWindow->assertNoEvents();
6541
6542 // Move to another window.
6543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6544 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6545 ADISPLAY_ID_DEFAULT, {150, 50}))
6546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6547 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6548 mWindow->consumeDragEvent(true, 150, 50);
6549 mSecondWindow->consumeDragEvent(false, 50, 50);
6550
6551 // Move back to original window.
6552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6553 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6554 ADISPLAY_ID_DEFAULT, {50, 50}))
6555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6556 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6557 mWindow->consumeDragEvent(false, 50, 50);
6558 mSecondWindow->consumeDragEvent(true, -50, 50);
6559
6560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6561 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6563 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6564 mWindow->assertNoEvents();
6565 mSecondWindow->assertNoEvents();
6566}
6567
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006568TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006569 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006570
6571 // No cancel event after drag start
6572 mSpyWindow->assertNoEvents();
6573
6574 const MotionEvent secondFingerDownEvent =
6575 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6576 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6577 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6578 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6579 .build();
6580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6581 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6582 InputEventInjectionSync::WAIT_FOR_RESULT))
6583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6584
6585 // Receives cancel for first pointer after next pointer down
6586 mSpyWindow->consumeMotionCancel();
6587 mSpyWindow->consumeMotionDown();
6588
6589 mSpyWindow->assertNoEvents();
6590}
6591
arthurhungf452d0b2021-01-06 00:19:52 +08006592TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006593 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006594
6595 // Move on window.
6596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6597 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6598 ADISPLAY_ID_DEFAULT, {50, 50}))
6599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6600 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6601 mWindow->consumeDragEvent(false, 50, 50);
6602 mSecondWindow->assertNoEvents();
6603
6604 // Move to another window.
6605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6606 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6607 ADISPLAY_ID_DEFAULT, {150, 50}))
6608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6609 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6610 mWindow->consumeDragEvent(true, 150, 50);
6611 mSecondWindow->consumeDragEvent(false, 50, 50);
6612
6613 // drop to another window.
6614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6615 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6616 {150, 50}))
6617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6618 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6619 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6620 mWindow->assertNoEvents();
6621 mSecondWindow->assertNoEvents();
6622}
6623
arthurhung6d4bed92021-03-17 11:59:33 +08006624TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006625 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006626
6627 // Move on window and keep button pressed.
6628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6629 injectMotionEvent(mDispatcher,
6630 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6631 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6632 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6633 .x(50)
6634 .y(50))
6635 .build()))
6636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6637 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6638 mWindow->consumeDragEvent(false, 50, 50);
6639 mSecondWindow->assertNoEvents();
6640
6641 // Move to another window and release button, expect to drop item.
6642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6643 injectMotionEvent(mDispatcher,
6644 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6645 .buttonState(0)
6646 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6647 .x(150)
6648 .y(50))
6649 .build()))
6650 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6651 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6652 mWindow->assertNoEvents();
6653 mSecondWindow->assertNoEvents();
6654 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6655
6656 // nothing to the window.
6657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6658 injectMotionEvent(mDispatcher,
6659 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6660 .buttonState(0)
6661 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6662 .x(150)
6663 .y(50))
6664 .build()))
6665 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6666 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6667 mWindow->assertNoEvents();
6668 mSecondWindow->assertNoEvents();
6669}
6670
Arthur Hung54745652022-04-20 07:17:41 +00006671TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006672 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006673
6674 // Set second window invisible.
6675 mSecondWindow->setVisible(false);
6676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6677
6678 // Move on window.
6679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6680 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6681 ADISPLAY_ID_DEFAULT, {50, 50}))
6682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6683 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6684 mWindow->consumeDragEvent(false, 50, 50);
6685 mSecondWindow->assertNoEvents();
6686
6687 // Move to another window.
6688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6689 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6690 ADISPLAY_ID_DEFAULT, {150, 50}))
6691 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6692 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6693 mWindow->consumeDragEvent(true, 150, 50);
6694 mSecondWindow->assertNoEvents();
6695
6696 // drop to another window.
6697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6698 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6699 {150, 50}))
6700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6701 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6702 mFakePolicy->assertDropTargetEquals(nullptr);
6703 mWindow->assertNoEvents();
6704 mSecondWindow->assertNoEvents();
6705}
6706
Arthur Hung54745652022-04-20 07:17:41 +00006707TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006708 // Ensure window could track pointerIds if it didn't support split touch.
6709 mWindow->setPreventSplitting(true);
6710
Arthur Hung54745652022-04-20 07:17:41 +00006711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6713 {50, 50}))
6714 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6715 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6716
6717 const MotionEvent secondFingerDownEvent =
6718 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6719 .displayId(ADISPLAY_ID_DEFAULT)
6720 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6721 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6722 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6723 .build();
6724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6725 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6726 InputEventInjectionSync::WAIT_FOR_RESULT))
6727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6728 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6729
6730 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006731 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006732}
6733
6734TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6735 // First down on second window.
6736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6738 {150, 50}))
6739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6740
6741 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6742
6743 // Second down on first window.
6744 const MotionEvent secondFingerDownEvent =
6745 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6746 .displayId(ADISPLAY_ID_DEFAULT)
6747 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6748 .pointer(
6749 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6750 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6751 .build();
6752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6753 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6754 InputEventInjectionSync::WAIT_FOR_RESULT))
6755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6756 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6757
6758 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006759 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006760
6761 // Move on window.
6762 const MotionEvent secondFingerMoveEvent =
6763 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6764 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6765 .pointer(
6766 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6767 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6768 .build();
6769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6770 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6771 InputEventInjectionSync::WAIT_FOR_RESULT));
6772 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6773 mWindow->consumeDragEvent(false, 50, 50);
6774 mSecondWindow->consumeMotionMove();
6775
6776 // Release the drag pointer should perform drop.
6777 const MotionEvent secondFingerUpEvent =
6778 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6779 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6780 .pointer(
6781 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6782 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6783 .build();
6784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6785 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6786 InputEventInjectionSync::WAIT_FOR_RESULT));
6787 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6788 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6789 mWindow->assertNoEvents();
6790 mSecondWindow->consumeMotionMove();
6791}
6792
Arthur Hung3915c1f2022-05-31 07:17:17 +00006793TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006794 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006795
6796 // Update window of second display.
6797 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006798 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006799 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6800
6801 // Let second display has a touch state.
6802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6803 injectMotionEvent(mDispatcher,
6804 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6805 AINPUT_SOURCE_TOUCHSCREEN)
6806 .displayId(SECOND_DISPLAY_ID)
6807 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6808 .x(100)
6809 .y(100))
6810 .build()));
6811 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6812 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6813 // Update window again.
6814 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6815
6816 // Move on window.
6817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6818 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6819 ADISPLAY_ID_DEFAULT, {50, 50}))
6820 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6821 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6822 mWindow->consumeDragEvent(false, 50, 50);
6823 mSecondWindow->assertNoEvents();
6824
6825 // Move to another window.
6826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6827 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6828 ADISPLAY_ID_DEFAULT, {150, 50}))
6829 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6830 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6831 mWindow->consumeDragEvent(true, 150, 50);
6832 mSecondWindow->consumeDragEvent(false, 50, 50);
6833
6834 // drop to another window.
6835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6836 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6837 {150, 50}))
6838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6839 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6840 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6841 mWindow->assertNoEvents();
6842 mSecondWindow->assertNoEvents();
6843}
6844
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006845TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6846 startDrag(true, AINPUT_SOURCE_MOUSE);
6847 // Move on window.
6848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6849 injectMotionEvent(mDispatcher,
6850 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6851 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6852 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6853 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6854 .x(50)
6855 .y(50))
6856 .build()))
6857 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6858 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6859 mWindow->consumeDragEvent(false, 50, 50);
6860 mSecondWindow->assertNoEvents();
6861
6862 // Move to another window.
6863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6864 injectMotionEvent(mDispatcher,
6865 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6866 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6867 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6868 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6869 .x(150)
6870 .y(50))
6871 .build()))
6872 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6873 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6874 mWindow->consumeDragEvent(true, 150, 50);
6875 mSecondWindow->consumeDragEvent(false, 50, 50);
6876
6877 // drop to another window.
6878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6879 injectMotionEvent(mDispatcher,
6880 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6881 .buttonState(0)
6882 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6883 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6884 .x(150)
6885 .y(50))
6886 .build()))
6887 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6888 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6889 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6890 mWindow->assertNoEvents();
6891 mSecondWindow->assertNoEvents();
6892}
6893
Vishnu Nair062a8672021-09-03 16:07:44 -07006894class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6895
6896TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6897 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006898 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6899 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006900 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006901 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6902 window->setFocusable(true);
6903 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6904 setFocusedWindow(window);
6905 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6906
6907 // With the flag set, window should not get any input
6908 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6909 mDispatcher->notifyKey(&keyArgs);
6910 window->assertNoEvents();
6911
6912 NotifyMotionArgs motionArgs =
6913 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6914 ADISPLAY_ID_DEFAULT);
6915 mDispatcher->notifyMotion(&motionArgs);
6916 window->assertNoEvents();
6917
6918 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006919 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6921
6922 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6923 mDispatcher->notifyKey(&keyArgs);
6924 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6925
6926 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6927 ADISPLAY_ID_DEFAULT);
6928 mDispatcher->notifyMotion(&motionArgs);
6929 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6930 window->assertNoEvents();
6931}
6932
6933TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6934 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6935 std::make_shared<FakeApplicationHandle>();
6936 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006937 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6938 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006939 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6940 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006941 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006942 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006943 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6944 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006945 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006946 window->setOwnerInfo(222, 222);
6947 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6948 window->setFocusable(true);
6949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6950 setFocusedWindow(window);
6951 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6952
6953 // With the flag set, window should not get any input
6954 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6955 mDispatcher->notifyKey(&keyArgs);
6956 window->assertNoEvents();
6957
6958 NotifyMotionArgs motionArgs =
6959 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6960 ADISPLAY_ID_DEFAULT);
6961 mDispatcher->notifyMotion(&motionArgs);
6962 window->assertNoEvents();
6963
6964 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006965 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6967
6968 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6969 mDispatcher->notifyKey(&keyArgs);
6970 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6971
6972 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6973 ADISPLAY_ID_DEFAULT);
6974 mDispatcher->notifyMotion(&motionArgs);
6975 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6976 window->assertNoEvents();
6977}
6978
6979TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6980 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6981 std::make_shared<FakeApplicationHandle>();
6982 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006983 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6984 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006985 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6986 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006987 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006988 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006989 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6990 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006991 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006992 window->setOwnerInfo(222, 222);
6993 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6994 window->setFocusable(true);
6995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6996 setFocusedWindow(window);
6997 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6998
6999 // With the flag set, window should not get any input
7000 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
7001 mDispatcher->notifyKey(&keyArgs);
7002 window->assertNoEvents();
7003
7004 NotifyMotionArgs motionArgs =
7005 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7006 ADISPLAY_ID_DEFAULT);
7007 mDispatcher->notifyMotion(&motionArgs);
7008 window->assertNoEvents();
7009
7010 // When the window is no longer obscured because it went on top, it should get input
7011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
7012
7013 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
7014 mDispatcher->notifyKey(&keyArgs);
7015 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
7016
7017 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7018 ADISPLAY_ID_DEFAULT);
7019 mDispatcher->notifyMotion(&motionArgs);
7020 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7021 window->assertNoEvents();
7022}
7023
Antonio Kantekf16f2832021-09-28 04:39:20 +00007024class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
7025protected:
7026 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00007027 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007028 sp<FakeWindowHandle> mWindow;
7029 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00007030 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00007031
7032 void SetUp() override {
7033 InputDispatcherTest::SetUp();
7034
7035 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00007036 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007037 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007038 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007039 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007040 mSecondWindow =
7041 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007042 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00007043 mThirdWindow =
7044 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
7045 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
7046 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007047
7048 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00007049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
7050 {SECOND_DISPLAY_ID, {mThirdWindow}}});
7051 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007052 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007053
Antonio Kantek15beb512022-06-13 22:35:41 +00007054 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00007055 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00007056 WINDOW_UID, true /* hasPermission */,
7057 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007058 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7059 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007060 mThirdWindow->assertNoEvents();
7061 }
7062
7063 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
7064 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
7065 SECONDARY_WINDOW_UID, true /* hasPermission */,
7066 SECOND_DISPLAY_ID)) {
7067 mWindow->assertNoEvents();
7068 mSecondWindow->assertNoEvents();
7069 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07007070 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007071 }
7072
Antonio Kantek15beb512022-06-13 22:35:41 +00007073 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
7074 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07007075 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
7076 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007077 mWindow->consumeTouchModeEvent(inTouchMode);
7078 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00007079 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00007080 }
7081};
7082
Antonio Kantek26defcf2022-02-08 01:12:27 +00007083TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007084 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00007085 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
7086 windowInfo.ownerPid, windowInfo.ownerUid,
7087 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007088}
7089
Antonio Kantek26defcf2022-02-08 01:12:27 +00007090TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7091 const WindowInfo& windowInfo = *mWindow->getInfo();
7092 int32_t ownerPid = windowInfo.ownerPid;
7093 int32_t ownerUid = windowInfo.ownerUid;
7094 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7095 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007096 ownerUid, false /*hasPermission*/,
7097 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00007098 mWindow->assertNoEvents();
7099 mSecondWindow->assertNoEvents();
7100}
7101
7102TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7103 const WindowInfo& windowInfo = *mWindow->getInfo();
7104 int32_t ownerPid = windowInfo.ownerPid;
7105 int32_t ownerUid = windowInfo.ownerUid;
7106 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00007107 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
7108 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007109}
7110
Antonio Kantekf16f2832021-09-28 04:39:20 +00007111TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007112 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007113 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7114 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007115 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007116 mWindow->assertNoEvents();
7117 mSecondWindow->assertNoEvents();
7118}
7119
Antonio Kantek15beb512022-06-13 22:35:41 +00007120TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
7121 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
7122 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7123 windowInfo.ownerPid, windowInfo.ownerUid,
7124 true /*hasPermission*/, SECOND_DISPLAY_ID));
7125 mWindow->assertNoEvents();
7126 mSecondWindow->assertNoEvents();
7127 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
7128}
7129
Antonio Kantek48710e42022-03-24 14:19:30 -07007130TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7131 // Interact with the window first.
7132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7133 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7134 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7135
7136 // Then remove focus.
7137 mWindow->setFocusable(false);
7138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7139
7140 // Assert that caller can switch touch mode by owning one of the last interacted window.
7141 const WindowInfo& windowInfo = *mWindow->getInfo();
7142 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7143 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07007144 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07007145}
7146
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007147class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7148public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007149 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007150 std::shared_ptr<FakeApplicationHandle> application =
7151 std::make_shared<FakeApplicationHandle>();
7152 std::string name = "Fake Spy ";
7153 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007154 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
7155 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007156 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007157 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007158 return spy;
7159 }
7160
7161 sp<FakeWindowHandle> createForeground() {
7162 std::shared_ptr<FakeApplicationHandle> application =
7163 std::make_shared<FakeApplicationHandle>();
7164 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007165 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
7166 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007167 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007168 return window;
7169 }
7170
7171private:
7172 int mSpyCount{0};
7173};
7174
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007175using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007176/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007177 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7178 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007179TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7180 ScopedSilentDeath _silentDeath;
7181
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007182 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007183 spy->setTrustedOverlay(false);
7184 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7185 ".* not a trusted overlay");
7186}
7187
7188/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007189 * Input injection into a display with a spy window but no foreground windows should succeed.
7190 */
7191TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007192 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7194
7195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7198 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7199}
7200
7201/**
7202 * Verify the order in which different input windows receive events. The touched foreground window
7203 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7204 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7205 * receive events before ones belows it.
7206 *
7207 * Here, we set up a scenario with four windows in the following Z order from the top:
7208 * spy1, spy2, window, spy3.
7209 * We then inject an event and verify that the foreground "window" receives it first, followed by
7210 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7211 * window.
7212 */
7213TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7214 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007215 auto spy1 = createSpy();
7216 auto spy2 = createSpy();
7217 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7219 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7220 const size_t numChannels = channels.size();
7221
Michael Wright8e9a8562022-02-09 13:44:29 +00007222 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007223 if (!epollFd.ok()) {
7224 FAIL() << "Failed to create epoll fd";
7225 }
7226
7227 for (size_t i = 0; i < numChannels; i++) {
7228 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7229 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7230 FAIL() << "Failed to add fd to epoll";
7231 }
7232 }
7233
7234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7235 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7236 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7237
7238 std::vector<size_t> eventOrder;
7239 std::vector<struct epoll_event> events(numChannels);
7240 for (;;) {
7241 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7242 (100ms).count());
7243 if (nFds < 0) {
7244 FAIL() << "Failed to call epoll_wait";
7245 }
7246 if (nFds == 0) {
7247 break; // epoll_wait timed out
7248 }
7249 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007250 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007251 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007252 channels[i]->consumeMotionDown();
7253 }
7254 }
7255
7256 // Verify the order in which the events were received.
7257 EXPECT_EQ(3u, eventOrder.size());
7258 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7259 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7260 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7261}
7262
7263/**
7264 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7265 */
7266TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7267 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007268 auto spy = createSpy();
7269 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7271
7272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7273 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7274 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7275 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7276 spy->assertNoEvents();
7277}
7278
7279/**
7280 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7281 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7282 * to the window.
7283 */
7284TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7285 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007286 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007287 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7289
7290 // Inject an event outside the spy window's touchable region.
7291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7292 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7293 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7294 window->consumeMotionDown();
7295 spy->assertNoEvents();
7296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7297 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7299 window->consumeMotionUp();
7300 spy->assertNoEvents();
7301
7302 // Inject an event inside the spy window's touchable region.
7303 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7304 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7305 {5, 10}))
7306 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7307 window->consumeMotionDown();
7308 spy->consumeMotionDown();
7309}
7310
7311/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007312 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007313 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007314 */
7315TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7316 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007317 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007318 auto spy = createSpy();
7319 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007320 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007321 spy->setFrame(Rect{0, 0, 20, 20});
7322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7323
7324 // Inject an event outside the spy window's frame and touchable region.
7325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007326 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7327 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007328 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7329 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007330 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007331}
7332
7333/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007334 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7335 * pointers that are down within its bounds.
7336 */
7337TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7338 auto windowLeft = createForeground();
7339 windowLeft->setFrame({0, 0, 100, 200});
7340 auto windowRight = createForeground();
7341 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007342 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007343 spy->setFrame({0, 0, 200, 200});
7344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7345
7346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7347 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7348 {50, 50}))
7349 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7350 windowLeft->consumeMotionDown();
7351 spy->consumeMotionDown();
7352
7353 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007354 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007355 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7356 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7357 .pointer(
7358 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7359 .build();
7360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7361 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7362 InputEventInjectionSync::WAIT_FOR_RESULT))
7363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7364 windowRight->consumeMotionDown();
7365 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7366}
7367
7368/**
7369 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7370 * the spy should receive the second pointer with ACTION_DOWN.
7371 */
7372TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7373 auto window = createForeground();
7374 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007375 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007376 spyRight->setFrame({100, 0, 200, 200});
7377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7378
7379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7381 {50, 50}))
7382 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7383 window->consumeMotionDown();
7384 spyRight->assertNoEvents();
7385
7386 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007387 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007388 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7389 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7390 .pointer(
7391 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7392 .build();
7393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7394 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7395 InputEventInjectionSync::WAIT_FOR_RESULT))
7396 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7397 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7398 spyRight->consumeMotionDown();
7399}
7400
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007401/**
7402 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7403 * windows should be allowed to control split touch.
7404 */
7405TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007406 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007407 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007408 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007409 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007410
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007411 auto window = createForeground();
7412 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007413
7414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7415
7416 // First finger down, no window touched.
7417 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7418 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7419 {100, 200}))
7420 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7421 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7422 window->assertNoEvents();
7423
7424 // Second finger down on window, the window should receive touch down.
7425 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007426 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007427 .displayId(ADISPLAY_ID_DEFAULT)
7428 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7429 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7430 .x(100)
7431 .y(200))
7432 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7433 .build();
7434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7435 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7436 InputEventInjectionSync::WAIT_FOR_RESULT))
7437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7438
7439 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7440 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7441}
7442
7443/**
7444 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7445 * do not receive key events.
7446 */
7447TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007448 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007449 spy->setFocusable(false);
7450
7451 auto window = createForeground();
7452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7453 setFocusedWindow(window);
7454 window->consumeFocusEvent(true);
7455
7456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7457 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7458 window->consumeKeyDown(ADISPLAY_ID_NONE);
7459
7460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7461 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7462 window->consumeKeyUp(ADISPLAY_ID_NONE);
7463
7464 spy->assertNoEvents();
7465}
7466
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007467using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7468
7469/**
7470 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7471 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7472 */
7473TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7474 auto window = createForeground();
7475 auto spy1 = createSpy();
7476 auto spy2 = createSpy();
7477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7478
7479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7480 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7481 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7482 window->consumeMotionDown();
7483 spy1->consumeMotionDown();
7484 spy2->consumeMotionDown();
7485
7486 // Pilfer pointers from the second spy window.
7487 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7488 spy2->assertNoEvents();
7489 spy1->consumeMotionCancel();
7490 window->consumeMotionCancel();
7491
7492 // The rest of the gesture should only be sent to the second spy window.
7493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7494 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7495 ADISPLAY_ID_DEFAULT))
7496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7497 spy2->consumeMotionMove();
7498 spy1->assertNoEvents();
7499 window->assertNoEvents();
7500}
7501
7502/**
7503 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7504 * in the middle of the gesture.
7505 */
7506TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7507 auto window = createForeground();
7508 auto spy = createSpy();
7509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7510
7511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7513 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7514 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7515 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7516
7517 window->releaseChannel();
7518
7519 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7520
7521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7522 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7523 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7524 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7525}
7526
7527/**
7528 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7529 * the spy, but not to any other windows.
7530 */
7531TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7532 auto spy = createSpy();
7533 auto window = createForeground();
7534
7535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7536
7537 // First finger down on the window and the spy.
7538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7540 {100, 200}))
7541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7542 spy->consumeMotionDown();
7543 window->consumeMotionDown();
7544
7545 // Spy window pilfers the pointers.
7546 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7547 window->consumeMotionCancel();
7548
7549 // Second finger down on the window and spy, but the window should not receive the pointer down.
7550 const MotionEvent secondFingerDownEvent =
7551 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7552 .displayId(ADISPLAY_ID_DEFAULT)
7553 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7554 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7555 .x(100)
7556 .y(200))
7557 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7558 .build();
7559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7560 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7561 InputEventInjectionSync::WAIT_FOR_RESULT))
7562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7563
7564 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7565
7566 // Third finger goes down outside all windows, so injection should fail.
7567 const MotionEvent thirdFingerDownEvent =
7568 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7569 .displayId(ADISPLAY_ID_DEFAULT)
7570 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7571 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7572 .x(100)
7573 .y(200))
7574 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7575 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7576 .build();
7577 ASSERT_EQ(InputEventInjectionResult::FAILED,
7578 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7579 InputEventInjectionSync::WAIT_FOR_RESULT))
7580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7581
7582 spy->assertNoEvents();
7583 window->assertNoEvents();
7584}
7585
7586/**
7587 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7588 */
7589TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7590 auto spy = createSpy();
7591 spy->setFrame(Rect(0, 0, 100, 100));
7592 auto window = createForeground();
7593 window->setFrame(Rect(0, 0, 200, 200));
7594
7595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7596
7597 // First finger down on the window only
7598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7600 {150, 150}))
7601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7602 window->consumeMotionDown();
7603
7604 // Second finger down on the spy and window
7605 const MotionEvent secondFingerDownEvent =
7606 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7607 .displayId(ADISPLAY_ID_DEFAULT)
7608 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7609 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7610 .x(150)
7611 .y(150))
7612 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7613 .build();
7614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7615 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7616 InputEventInjectionSync::WAIT_FOR_RESULT))
7617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7618 spy->consumeMotionDown();
7619 window->consumeMotionPointerDown(1);
7620
7621 // Third finger down on the spy and window
7622 const MotionEvent thirdFingerDownEvent =
7623 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7624 .displayId(ADISPLAY_ID_DEFAULT)
7625 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7626 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7627 .x(150)
7628 .y(150))
7629 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7630 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7631 .build();
7632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7633 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7634 InputEventInjectionSync::WAIT_FOR_RESULT))
7635 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7636 spy->consumeMotionPointerDown(1);
7637 window->consumeMotionPointerDown(2);
7638
7639 // Spy window pilfers the pointers.
7640 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7641 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7642 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7643
7644 spy->assertNoEvents();
7645 window->assertNoEvents();
7646}
7647
7648/**
7649 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7650 * other windows should be canceled. If this results in the cancellation of all pointers for some
7651 * window, then that window should receive ACTION_CANCEL.
7652 */
7653TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7654 auto spy = createSpy();
7655 spy->setFrame(Rect(0, 0, 100, 100));
7656 auto window = createForeground();
7657 window->setFrame(Rect(0, 0, 200, 200));
7658
7659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7660
7661 // First finger down on both spy and window
7662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7663 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7664 {10, 10}))
7665 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7666 window->consumeMotionDown();
7667 spy->consumeMotionDown();
7668
7669 // Second finger down on the spy and window
7670 const MotionEvent secondFingerDownEvent =
7671 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7672 .displayId(ADISPLAY_ID_DEFAULT)
7673 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7674 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7675 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7676 .build();
7677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7678 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7679 InputEventInjectionSync::WAIT_FOR_RESULT))
7680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7681 spy->consumeMotionPointerDown(1);
7682 window->consumeMotionPointerDown(1);
7683
7684 // Spy window pilfers the pointers.
7685 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7686 window->consumeMotionCancel();
7687
7688 spy->assertNoEvents();
7689 window->assertNoEvents();
7690}
7691
7692/**
7693 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7694 * be sent to other windows
7695 */
7696TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7697 auto spy = createSpy();
7698 spy->setFrame(Rect(0, 0, 100, 100));
7699 auto window = createForeground();
7700 window->setFrame(Rect(0, 0, 200, 200));
7701
7702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7703
7704 // First finger down on both window and spy
7705 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7706 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7707 {10, 10}))
7708 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7709 window->consumeMotionDown();
7710 spy->consumeMotionDown();
7711
7712 // Spy window pilfers the pointers.
7713 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7714 window->consumeMotionCancel();
7715
7716 // Second finger down on the window only
7717 const MotionEvent secondFingerDownEvent =
7718 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7719 .displayId(ADISPLAY_ID_DEFAULT)
7720 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7721 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7722 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7723 .x(150)
7724 .y(150))
7725 .build();
7726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7727 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7728 InputEventInjectionSync::WAIT_FOR_RESULT))
7729 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7730 window->consumeMotionDown();
7731 window->assertNoEvents();
7732
7733 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7734 spy->consumeMotionMove();
7735 spy->assertNoEvents();
7736}
7737
Prabir Pradhand65552b2021-10-07 11:23:50 -07007738class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7739public:
7740 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7741 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7742 std::make_shared<FakeApplicationHandle>();
7743 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007744 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7745 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007746 overlay->setFocusable(false);
7747 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007748 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007749 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007750 overlay->setTrustedOverlay(true);
7751
7752 std::shared_ptr<FakeApplicationHandle> application =
7753 std::make_shared<FakeApplicationHandle>();
7754 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007755 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7756 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007757 window->setFocusable(true);
7758 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007759
7760 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7762 setFocusedWindow(window);
7763 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7764 return {std::move(overlay), std::move(window)};
7765 }
7766
7767 void sendFingerEvent(int32_t action) {
7768 NotifyMotionArgs motionArgs =
7769 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7770 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7771 mDispatcher->notifyMotion(&motionArgs);
7772 }
7773
7774 void sendStylusEvent(int32_t action) {
7775 NotifyMotionArgs motionArgs =
7776 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7777 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7778 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7779 mDispatcher->notifyMotion(&motionArgs);
7780 }
7781};
7782
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007783using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7784
7785TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7786 ScopedSilentDeath _silentDeath;
7787
Prabir Pradhand65552b2021-10-07 11:23:50 -07007788 auto [overlay, window] = setupStylusOverlayScenario();
7789 overlay->setTrustedOverlay(false);
7790 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7791 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7792 ".* not a trusted overlay");
7793}
7794
7795TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7796 auto [overlay, window] = setupStylusOverlayScenario();
7797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7798
7799 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7800 overlay->consumeMotionDown();
7801 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7802 overlay->consumeMotionUp();
7803
7804 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7805 window->consumeMotionDown();
7806 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7807 window->consumeMotionUp();
7808
7809 overlay->assertNoEvents();
7810 window->assertNoEvents();
7811}
7812
7813TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7814 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007815 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007816 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7817
7818 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7819 overlay->consumeMotionDown();
7820 window->consumeMotionDown();
7821 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7822 overlay->consumeMotionUp();
7823 window->consumeMotionUp();
7824
7825 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7826 window->consumeMotionDown();
7827 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7828 window->consumeMotionUp();
7829
7830 overlay->assertNoEvents();
7831 window->assertNoEvents();
7832}
7833
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007834/**
7835 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7836 * The scenario is as follows:
7837 * - The stylus interceptor overlay is configured as a spy window.
7838 * - The stylus interceptor spy receives the start of a new stylus gesture.
7839 * - It pilfers pointers and then configures itself to no longer be a spy.
7840 * - The stylus interceptor continues to receive the rest of the gesture.
7841 */
7842TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7843 auto [overlay, window] = setupStylusOverlayScenario();
7844 overlay->setSpy(true);
7845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7846
7847 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7848 overlay->consumeMotionDown();
7849 window->consumeMotionDown();
7850
7851 // The interceptor pilfers the pointers.
7852 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7853 window->consumeMotionCancel();
7854
7855 // The interceptor configures itself so that it is no longer a spy.
7856 overlay->setSpy(false);
7857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7858
7859 // It continues to receive the rest of the stylus gesture.
7860 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7861 overlay->consumeMotionMove();
7862 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7863 overlay->consumeMotionUp();
7864
7865 window->assertNoEvents();
7866}
7867
Prabir Pradhan5735a322022-04-11 17:23:34 +00007868struct User {
7869 int32_t mPid;
7870 int32_t mUid;
7871 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7872 std::unique_ptr<InputDispatcher>& mDispatcher;
7873
7874 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7875 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7876
7877 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7878 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7879 ADISPLAY_ID_DEFAULT, {100, 200},
7880 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7881 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7882 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7883 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7884 }
7885
7886 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7887 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7888 InputEventInjectionSync::WAIT_FOR_RESULT,
7889 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7890 mPolicyFlags);
7891 }
7892
7893 sp<FakeWindowHandle> createWindow() const {
7894 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7895 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007896 sp<FakeWindowHandle> window =
7897 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7898 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007899 window->setOwnerInfo(mPid, mUid);
7900 return window;
7901 }
7902};
7903
7904using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7905
7906TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7907 auto owner = User(mDispatcher, 10, 11);
7908 auto window = owner.createWindow();
7909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7910
7911 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7912 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7913 window->consumeMotionDown();
7914
7915 setFocusedWindow(window);
7916 window->consumeFocusEvent(true);
7917
7918 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7919 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7920 window->consumeKeyDown(ADISPLAY_ID_NONE);
7921}
7922
7923TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7924 auto owner = User(mDispatcher, 10, 11);
7925 auto window = owner.createWindow();
7926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7927
7928 auto rando = User(mDispatcher, 20, 21);
7929 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7930 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7931
7932 setFocusedWindow(window);
7933 window->consumeFocusEvent(true);
7934
7935 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7936 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7937 window->assertNoEvents();
7938}
7939
7940TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7941 auto owner = User(mDispatcher, 10, 11);
7942 auto window = owner.createWindow();
7943 auto spy = owner.createWindow();
7944 spy->setSpy(true);
7945 spy->setTrustedOverlay(true);
7946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7947
7948 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7949 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7950 spy->consumeMotionDown();
7951 window->consumeMotionDown();
7952}
7953
7954TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7955 auto owner = User(mDispatcher, 10, 11);
7956 auto window = owner.createWindow();
7957
7958 auto rando = User(mDispatcher, 20, 21);
7959 auto randosSpy = rando.createWindow();
7960 randosSpy->setSpy(true);
7961 randosSpy->setTrustedOverlay(true);
7962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7963
7964 // The event is targeted at owner's window, so injection should succeed, but the spy should
7965 // not receive the event.
7966 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7967 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7968 randosSpy->assertNoEvents();
7969 window->consumeMotionDown();
7970}
7971
7972TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7973 auto owner = User(mDispatcher, 10, 11);
7974 auto window = owner.createWindow();
7975
7976 auto rando = User(mDispatcher, 20, 21);
7977 auto randosSpy = rando.createWindow();
7978 randosSpy->setSpy(true);
7979 randosSpy->setTrustedOverlay(true);
7980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7981
7982 // A user that has injection permission can inject into any window.
7983 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7984 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7985 ADISPLAY_ID_DEFAULT));
7986 randosSpy->consumeMotionDown();
7987 window->consumeMotionDown();
7988
7989 setFocusedWindow(randosSpy);
7990 randosSpy->consumeFocusEvent(true);
7991
7992 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7993 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7994 window->assertNoEvents();
7995}
7996
7997TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7998 auto owner = User(mDispatcher, 10, 11);
7999 auto window = owner.createWindow();
8000
8001 auto rando = User(mDispatcher, 20, 21);
8002 auto randosWindow = rando.createWindow();
8003 randosWindow->setFrame(Rect{-10, -10, -5, -5});
8004 randosWindow->setWatchOutsideTouch(true);
8005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
8006
8007 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
8008 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
8009 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
8010 window->consumeMotionDown();
8011 randosWindow->consumeMotionOutside();
8012}
8013
Garfield Tane84e6f92019-08-29 17:28:41 -07008014} // namespace android::inputdispatcher