blob: b23b88adb4a091e38f776ba6eb293cf7ea0437b5 [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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080028#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100029
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070031#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080032#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080033#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080034
Garfield Tan1c7bc862020-01-28 13:24:04 -080035using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050036using android::gui::FocusRequest;
37using android::gui::TouchOcclusionMode;
38using android::gui::WindowInfo;
39using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080040using android::os::InputEventInjectionResult;
41using android::os::InputEventInjectionSync;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
Dominik Laskowski2f01d772022-03-23 16:01:29 -070045using namespace ftl::flag_operators;
46
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary time value.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000048static constexpr nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
50// An arbitrary device id.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000051static constexpr int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Jeff Brownf086ddb2014-02-11 14:28:48 -080053// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000054static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
55static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080056
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080057static constexpr int32_t POINTER_1_DOWN =
58 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000059static constexpr int32_t POINTER_2_DOWN =
60 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Arthur Hungba703c32022-12-08 07:45:36 +000061static constexpr int32_t POINTER_0_UP =
62 AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080063static constexpr int32_t POINTER_1_UP =
64 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
65
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000066// The default pid and uid for windows created by the test.
67static constexpr int32_t WINDOW_PID = 999;
68static constexpr int32_t WINDOW_UID = 1001;
69
70// The default policy flags to use for event injection by tests.
71static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000073// An arbitrary pid of the gesture monitor window
74static constexpr int32_t MONITOR_PID = 2001;
75
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080076static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
77
Arthur Hungba703c32022-12-08 07:45:36 +000078static constexpr int expectedWallpaperFlags =
79 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
80
chaviwd1c23182019-12-20 18:44:56 -080081struct PointF {
82 float x;
83 float y;
84};
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
Gang Wang342c9272020-01-13 13:15:04 -050086/**
87 * Return a DOWN key event with KEYCODE_A.
88 */
89static KeyEvent getTestKeyEvent() {
90 KeyEvent event;
91
Garfield Tanfbe732e2020-01-24 11:26:14 -080092 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
93 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
94 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050095 return event;
96}
97
Siarhei Vishniakouca205502021-07-16 21:31:58 +000098static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
99 ASSERT_EQ(expectedAction, receivedAction)
100 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
101 << MotionEvent::actionToString(receivedAction);
102}
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// --- FakeInputDispatcherPolicy ---
105
106class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
107 InputDispatcherConfiguration mConfig;
108
Prabir Pradhanedd96402022-02-15 01:46:16 -0800109 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
110
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000112 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113
114public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000115 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800116
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800117 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700118 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
119 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
120 EXPECT_EQ(event.getDisplayId(), args.displayId);
121
122 const auto& keyEvent = static_cast<const KeyEvent&>(event);
123 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
124 EXPECT_EQ(keyEvent.getAction(), args.action);
125 });
Jackal Guof9696682018-10-05 12:23:23 +0800126 }
127
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700128 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
129 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
130 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
131 EXPECT_EQ(event.getDisplayId(), args.displayId);
132
133 const auto& motionEvent = static_cast<const MotionEvent&>(event);
134 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
135 EXPECT_EQ(motionEvent.getAction(), args.action);
Prabir Pradhan0909dc12023-03-09 20:11:09 +0000136 EXPECT_NEAR(motionEvent.getX(0), point.x, MotionEvent::ROUNDING_PRECISION);
137 EXPECT_NEAR(motionEvent.getY(0), point.y, MotionEvent::ROUNDING_PRECISION);
138 EXPECT_NEAR(motionEvent.getRawX(0), point.x, MotionEvent::ROUNDING_PRECISION);
139 EXPECT_NEAR(motionEvent.getRawY(0), point.y, MotionEvent::ROUNDING_PRECISION);
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700140 });
Jackal Guof9696682018-10-05 12:23:23 +0800141 }
142
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700143 void assertFilterInputEventWasNotCalled() {
144 std::scoped_lock lock(mLock);
145 ASSERT_EQ(nullptr, mFilteredEvent);
146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800148 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700149 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800150 ASSERT_TRUE(mConfigurationChangedTime)
151 << "Timed out waiting for configuration changed call";
152 ASSERT_EQ(*mConfigurationChangedTime, when);
153 mConfigurationChangedTime = std::nullopt;
154 }
155
156 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700157 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800158 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800159 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800160 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
161 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
162 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
163 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
164 mLastNotifySwitch = std::nullopt;
165 }
166
chaviwfd6d3512019-03-25 13:23:49 -0700167 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700168 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800169 ASSERT_EQ(touchedToken, mOnPointerDownToken);
170 mOnPointerDownToken.clear();
171 }
172
173 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700174 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800175 ASSERT_TRUE(mOnPointerDownToken == nullptr)
176 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700177 }
178
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700179 // This function must be called soon after the expected ANR timer starts,
180 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500181 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700182 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500183 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800184 std::unique_lock lock(mLock);
185 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800187 ASSERT_NO_FATAL_FAILURE(
188 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500189 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700190 }
191
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000192 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800193 const sp<WindowInfoHandle>& window) {
194 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
195 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
196 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500197 }
198
Prabir Pradhanedd96402022-02-15 01:46:16 -0800199 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
200 const sp<IBinder>& expectedToken,
201 int32_t expectedPid) {
202 std::unique_lock lock(mLock);
203 android::base::ScopedLockAssertion assumeLocked(mLock);
204 AnrResult result;
205 ASSERT_NO_FATAL_FAILURE(result =
206 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
207 const auto& [token, pid] = result;
208 ASSERT_EQ(expectedToken, token);
209 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500210 }
211
Prabir Pradhanedd96402022-02-15 01:46:16 -0800212 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000213 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500214 std::unique_lock lock(mLock);
215 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800216 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
217 const auto& [token, _] = result;
218 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000219 }
220
Prabir Pradhanedd96402022-02-15 01:46:16 -0800221 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
222 int32_t expectedPid) {
223 std::unique_lock lock(mLock);
224 android::base::ScopedLockAssertion assumeLocked(mLock);
225 AnrResult result;
226 ASSERT_NO_FATAL_FAILURE(
227 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
228 const auto& [token, pid] = result;
229 ASSERT_EQ(expectedToken, token);
230 ASSERT_EQ(expectedPid, pid);
231 }
232
233 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000234 sp<IBinder> getResponsiveWindowToken() {
235 std::unique_lock lock(mLock);
236 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800237 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
238 const auto& [token, _] = result;
239 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700240 }
241
242 void assertNotifyAnrWasNotCalled() {
243 std::scoped_lock lock(mLock);
244 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800245 ASSERT_TRUE(mAnrWindows.empty());
246 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500247 << "ANR was not called, but please also consume the 'connection is responsive' "
248 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700249 }
250
Garfield Tan1c7bc862020-01-28 13:24:04 -0800251 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
252 mConfig.keyRepeatTimeout = timeout;
253 mConfig.keyRepeatDelay = delay;
254 }
255
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000256 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800257 std::unique_lock lock(mLock);
258 base::ScopedLockAssertion assumeLocked(mLock);
259
260 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
261 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000262 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800263 enabled;
264 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000265 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
266 << ") to be called.";
267 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800268 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000269 auto request = *mPointerCaptureRequest;
270 mPointerCaptureRequest.reset();
271 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800272 }
273
274 void assertSetPointerCaptureNotCalled() {
275 std::unique_lock lock(mLock);
276 base::ScopedLockAssertion assumeLocked(mLock);
277
278 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000279 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800280 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000281 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800282 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000283 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800284 }
285
arthurhungf452d0b2021-01-06 00:19:52 +0800286 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
287 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800288 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800289 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800290 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800291 }
292
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800293 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
294 std::unique_lock lock(mLock);
295 base::ScopedLockAssertion assumeLocked(mLock);
296 std::optional<sp<IBinder>> receivedToken =
297 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
298 mNotifyInputChannelBroken);
299 ASSERT_TRUE(receivedToken.has_value());
300 ASSERT_EQ(token, *receivedToken);
301 }
302
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800303 /**
304 * Set policy timeout. A value of zero means next key will not be intercepted.
305 */
306 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
307 mInterceptKeyTimeout = timeout;
308 }
309
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700311 std::mutex mLock;
312 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
313 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
314 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
315 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800316
Prabir Pradhan99987712020-11-10 18:43:05 -0800317 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000318
319 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800320
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700321 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700322 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800323 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
324 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700325 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800326 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
327 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700328
arthurhungf452d0b2021-01-06 00:19:52 +0800329 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800330 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800331
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800332 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
333
Prabir Pradhanedd96402022-02-15 01:46:16 -0800334 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
335 // for a specific container to become non-empty. When the container is non-empty, return the
336 // first entry from the container and erase it.
337 template <class T>
338 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
339 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
340 // If there is an ANR, Dispatcher won't be idle because there are still events
341 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
342 // before checking if ANR was called.
343 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
344 // to provide it some time to act. 100ms seems reasonable.
345 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
346 const std::chrono::time_point start = std::chrono::steady_clock::now();
347 std::optional<T> token =
348 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
349 if (!token.has_value()) {
350 ADD_FAILURE() << "Did not receive the ANR callback";
351 return {};
352 }
353
354 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
355 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
356 // the dispatcher started counting before this function was called
357 if (std::chrono::abs(timeout - waited) > 100ms) {
358 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
359 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
360 << "ms, but waited "
361 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
362 << "ms instead";
363 }
364 return *token;
365 }
366
367 template <class T>
368 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
369 std::queue<T>& storage,
370 std::unique_lock<std::mutex>& lock,
371 std::condition_variable& condition)
372 REQUIRES(mLock) {
373 condition.wait_for(lock, timeout,
374 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
375 if (storage.empty()) {
376 ADD_FAILURE() << "Did not receive the expected callback";
377 return std::nullopt;
378 }
379 T item = storage.front();
380 storage.pop();
381 return std::make_optional(item);
382 }
383
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600384 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700385 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800386 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800387 }
388
Prabir Pradhanedd96402022-02-15 01:46:16 -0800389 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
390 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700391 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800392 ASSERT_TRUE(pid.has_value());
393 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700394 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500395 }
396
Prabir Pradhanedd96402022-02-15 01:46:16 -0800397 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
398 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500399 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800400 ASSERT_TRUE(pid.has_value());
401 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500402 mNotifyAnr.notify_all();
403 }
404
405 void notifyNoFocusedWindowAnr(
406 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
407 std::scoped_lock lock(mLock);
408 mAnrApplications.push(applicationHandle);
409 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 }
411
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800412 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
413 std::scoped_lock lock(mLock);
414 mBrokenInputChannels.push(connectionToken);
415 mNotifyInputChannelBroken.notify_all();
416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600418 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700419
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600420 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700421 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
422 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
423 const std::vector<float>& values) override {}
424
425 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
426 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000427
Chris Yefb552902021-02-03 17:18:37 -0800428 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
429
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600430 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 *outConfig = mConfig;
432 }
433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700435 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800436 switch (inputEvent->getType()) {
437 case AINPUT_EVENT_TYPE_KEY: {
438 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800439 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800440 break;
441 }
442
443 case AINPUT_EVENT_TYPE_MOTION: {
444 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800445 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800446 break;
447 }
448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 return true;
450 }
451
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800452 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
453 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
454 // Clear intercept state when we handled the event.
455 mInterceptKeyTimeout = 0ms;
456 }
457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600459 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600461 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800462 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
463 // Clear intercept state so we could dispatch the event in next wake.
464 mInterceptKeyTimeout = 0ms;
465 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 }
467
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600468 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 return false;
470 }
471
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600472 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
473 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700474 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800475 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
476 * essentially a passthrough for notifySwitch.
477 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800478 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 }
480
Sean Stoutb4e0a592021-02-23 07:34:53 -0800481 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600483 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700484 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700485 mOnPointerDownToken = newToken;
486 }
487
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000488 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800489 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000490 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800491 mPointerCaptureChangedCondition.notify_all();
492 }
493
arthurhungf452d0b2021-01-06 00:19:52 +0800494 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
495 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800496 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800497 mDropTargetWindowToken = token;
498 }
499
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700500 void assertFilterInputEventWasCalledInternal(
501 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700502 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800503 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700504 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800505 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507};
508
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509// --- InputDispatcherTest ---
510
511class InputDispatcherTest : public testing::Test {
512protected:
513 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700514 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000516 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800518 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800519 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000520 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700521 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000524 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700525 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700527 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700529
530 /**
531 * Used for debugging when writing the test
532 */
533 void dumpDispatcherState() {
534 std::string dump;
535 mDispatcher->dump(dump);
536 std::stringstream ss(dump);
537 std::string to;
538
539 while (std::getline(ss, to, '\n')) {
540 ALOGE("%s", to.c_str());
541 }
542 }
Vishnu Nair958da932020-08-21 17:12:37 -0700543
chaviw3277faf2021-05-19 16:45:23 -0500544 void setFocusedWindow(const sp<WindowInfoHandle>& window,
545 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700546 FocusRequest request;
547 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000548 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700549 if (focusedWindow) {
550 request.focusedToken = focusedWindow->getToken();
551 }
552 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
553 request.displayId = window->getInfo()->displayId;
554 mDispatcher->setFocusedWindow(request);
555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556};
557
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
559 KeyEvent event;
560
561 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800562 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
563 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600564 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
565 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800566 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000567 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
568 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569 << "Should reject key events with undefined action.";
570
571 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800572 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
573 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600574 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800575 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000576 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
577 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 << "Should reject key events with ACTION_MULTIPLE.";
579}
580
581TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
582 MotionEvent event;
583 PointerProperties pointerProperties[MAX_POINTERS + 1];
584 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800585 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 pointerProperties[i].clear();
587 pointerProperties[i].id = i;
588 pointerCoords[i].clear();
589 }
590
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800591 // Some constants commonly used below
592 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
593 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
594 constexpr int32_t metaState = AMETA_NONE;
595 constexpr MotionClassification classification = MotionClassification::NONE;
596
chaviw9eaa22c2020-07-01 16:21:27 -0700597 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800599 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700600 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
601 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700602 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
603 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000606 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
607 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with undefined action.";
609
610 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800612 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
613 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
614 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
615 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500616 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800617 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000618 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
619 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 << "Should reject motion events with pointer down index too large.";
621
Garfield Tanfbe732e2020-01-24 11:26:14 -0800622 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700623 AMOTION_EVENT_ACTION_POINTER_DOWN |
624 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700625 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
626 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700627 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500628 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-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 pointer down index too small.";
633
634 // Rejects pointer up 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_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
637 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 Pradhan8a2b1a42022-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 up 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_UP |
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 Pradhan8a2b1a42022-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 up index too small.";
657
658 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800659 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
660 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700661 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
663 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-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 0 pointers.";
669
Garfield Tanfbe732e2020-01-24 11:26:14 -0800670 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
671 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700672 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700673 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
674 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700675 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800676 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000677 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
678 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 << "Should reject motion events with more than MAX_POINTERS pointers.";
680
681 // Rejects motion events with invalid pointer ids.
682 pointerProperties[0].id = -1;
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*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800689 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-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 pointer ids less than 0.";
693
694 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800695 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
696 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700697 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700698 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
699 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700700 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800701 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000702 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
703 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
705
706 // Rejects motion events with duplicate pointer ids.
707 pointerProperties[0].id = 1;
708 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800709 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
710 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700711 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700712 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
713 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700714 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800715 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000716 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
717 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 << "Should reject motion events with duplicate pointer ids.";
719}
720
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800721/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
722
723TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
724 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800725 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800726 mDispatcher->notifyConfigurationChanged(&args);
727 ASSERT_TRUE(mDispatcher->waitForIdle());
728
729 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
730}
731
732TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800733 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
734 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800735 mDispatcher->notifySwitch(&args);
736
737 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
738 args.policyFlags |= POLICY_FLAG_TRUSTED;
739 mFakePolicy->assertNotifySwitchWasCalled(args);
740}
741
Arthur Hungb92218b2018-08-14 12:00:21 +0800742// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700743static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700744// Default input dispatching timeout if there is no focused application or paused window
745// from which to determine an appropriate dispatching timeout.
746static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
747 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
748 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800749
750class FakeApplicationHandle : public InputApplicationHandle {
751public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 FakeApplicationHandle() {
753 mInfo.name = "Fake Application";
754 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500755 mInfo.dispatchingTimeoutMillis =
756 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700757 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800758 virtual ~FakeApplicationHandle() {}
759
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000760 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700761
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500762 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
763 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700764 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800765};
766
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800767class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800768public:
Garfield Tan15601662020-09-22 15:32:38 -0700769 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800770 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700771 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800772 }
773
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800774 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700775 InputEvent* event;
776 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
777 if (!consumeSeq) {
778 return nullptr;
779 }
780 finishEvent(*consumeSeq);
781 return event;
782 }
783
784 /**
785 * Receive an event without acknowledging it.
786 * Return the sequence number that could later be used to send finished signal.
787 */
788 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800789 uint32_t consumeSeq;
790 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800791
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792 std::chrono::time_point start = std::chrono::steady_clock::now();
793 status_t status = WOULD_BLOCK;
794 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800795 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800796 &event);
797 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
798 if (elapsed > 100ms) {
799 break;
800 }
801 }
802
803 if (status == WOULD_BLOCK) {
804 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700805 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800806 }
807
808 if (status != OK) {
809 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700810 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800811 }
812 if (event == nullptr) {
813 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700814 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700816 if (outEvent != nullptr) {
817 *outEvent = event;
818 }
819 return consumeSeq;
820 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800821
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700822 /**
823 * To be used together with "receiveEvent" to complete the consumption of an event.
824 */
825 void finishEvent(uint32_t consumeSeq) {
826 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
827 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800828 }
829
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000830 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
831 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
832 ASSERT_EQ(OK, status);
833 }
834
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000835 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
836 std::optional<int32_t> expectedDisplayId,
837 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800838 InputEvent* event = consume();
839
840 ASSERT_NE(nullptr, event) << mName.c_str()
841 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800842 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800844 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800845
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000846 if (expectedDisplayId.has_value()) {
847 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
848 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800849
Tiger Huang8664f8c2018-10-11 19:14:35 +0800850 switch (expectedEventType) {
851 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800852 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
853 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000854 if (expectedFlags.has_value()) {
855 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
856 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800857 break;
858 }
859 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800860 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000861 assertMotionAction(expectedAction, motionEvent.getAction());
862
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000863 if (expectedFlags.has_value()) {
864 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
865 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800866 break;
867 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100868 case AINPUT_EVENT_TYPE_FOCUS: {
869 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
870 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800871 case AINPUT_EVENT_TYPE_CAPTURE: {
872 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
873 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000874 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
875 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
876 }
arthurhungb89ccb02020-12-30 16:19:01 +0800877 case AINPUT_EVENT_TYPE_DRAG: {
878 FAIL() << "Use 'consumeDragEvent' for DRAG events";
879 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800880 default: {
881 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
882 }
883 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800884 }
885
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100886 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
887 InputEvent* event = consume();
888 ASSERT_NE(nullptr, event) << mName.c_str()
889 << ": consumer should have returned non-NULL event.";
890 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
891 << "Got " << inputEventTypeToString(event->getType())
892 << " event instead of FOCUS event";
893
894 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
895 << mName.c_str() << ": event displayId should always be NONE.";
896
897 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
898 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100899 }
900
Prabir Pradhan99987712020-11-10 18:43:05 -0800901 void consumeCaptureEvent(bool hasCapture) {
902 const InputEvent* event = consume();
903 ASSERT_NE(nullptr, event) << mName.c_str()
904 << ": consumer should have returned non-NULL event.";
905 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
906 << "Got " << inputEventTypeToString(event->getType())
907 << " event instead of CAPTURE event";
908
909 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
910 << mName.c_str() << ": event displayId should always be NONE.";
911
912 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
913 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
914 }
915
arthurhungb89ccb02020-12-30 16:19:01 +0800916 void consumeDragEvent(bool isExiting, float x, float y) {
917 const InputEvent* event = consume();
918 ASSERT_NE(nullptr, event) << mName.c_str()
919 << ": consumer should have returned non-NULL event.";
920 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
921 << "Got " << inputEventTypeToString(event->getType())
922 << " event instead of DRAG event";
923
924 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
925 << mName.c_str() << ": event displayId should always be NONE.";
926
927 const auto& dragEvent = static_cast<const DragEvent&>(*event);
928 EXPECT_EQ(isExiting, dragEvent.isExiting());
929 EXPECT_EQ(x, dragEvent.getX());
930 EXPECT_EQ(y, dragEvent.getY());
931 }
932
Antonio Kantekf16f2832021-09-28 04:39:20 +0000933 void consumeTouchModeEvent(bool inTouchMode) {
934 const InputEvent* event = consume();
935 ASSERT_NE(nullptr, event) << mName.c_str()
936 << ": consumer should have returned non-NULL event.";
937 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
938 << "Got " << inputEventTypeToString(event->getType())
939 << " event instead of TOUCH_MODE event";
940
941 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
942 << mName.c_str() << ": event displayId should always be NONE.";
943 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
944 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
945 }
946
chaviwd1c23182019-12-20 18:44:56 -0800947 void assertNoEvents() {
948 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 if (event == nullptr) {
950 return;
951 }
952 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
953 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
954 ADD_FAILURE() << "Received key event "
955 << KeyEvent::actionToString(keyEvent.getAction());
956 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
957 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
958 ADD_FAILURE() << "Received motion event "
959 << MotionEvent::actionToString(motionEvent.getAction());
960 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
961 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
962 ADD_FAILURE() << "Received focus event, hasFocus = "
963 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800964 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
965 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
966 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
967 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000968 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
969 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
970 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
971 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700972 }
973 FAIL() << mName.c_str()
974 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800975 }
976
977 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
978
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800979 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
980
chaviwd1c23182019-12-20 18:44:56 -0800981protected:
982 std::unique_ptr<InputConsumer> mConsumer;
983 PreallocatedInputEventFactory mEventFactory;
984
985 std::string mName;
986};
987
chaviw3277faf2021-05-19 16:45:23 -0500988class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800989public:
990 static const int32_t WIDTH = 600;
991 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800992
Chris Yea209fde2020-07-22 13:54:51 -0700993 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700994 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500995 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800996 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500997 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700998 base::Result<std::unique_ptr<InputChannel>> channel =
999 dispatcher->createInputChannel(name);
1000 token = (*channel)->getConnectionToken();
1001 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001002 }
1003
1004 inputApplicationHandle->updateInfo();
1005 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1006
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001007 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001008 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001009 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001010 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001011 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001012 mInfo.frameLeft = 0;
1013 mInfo.frameTop = 0;
1014 mInfo.frameRight = WIDTH;
1015 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001016 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001017 mInfo.globalScaleFactor = 1.0;
1018 mInfo.touchableRegion.clear();
1019 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001020 mInfo.ownerPid = WINDOW_PID;
1021 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001022 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001023 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001024 }
1025
Arthur Hungabbb9d82021-09-01 14:52:30 +00001026 sp<FakeWindowHandle> clone(
1027 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001028 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001029 sp<FakeWindowHandle> handle =
1030 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1031 displayId, mInfo.token);
1032 return handle;
1033 }
1034
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001035 void setTouchable(bool touchable) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1037 }
chaviwd1c23182019-12-20 18:44:56 -08001038
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001039 void setFocusable(bool focusable) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1041 }
1042
1043 void setVisible(bool visible) {
1044 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1045 }
Vishnu Nair958da932020-08-21 17:12:37 -07001046
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001047 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001048 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001049 }
1050
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001051 void setPaused(bool paused) {
1052 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1053 }
1054
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001055 void setPreventSplitting(bool preventSplitting) {
1056 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001057 }
1058
1059 void setSlippery(bool slippery) {
1060 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1061 }
1062
1063 void setWatchOutsideTouch(bool watchOutside) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1065 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001067 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1068
1069 void setInterceptsStylus(bool interceptsStylus) {
1070 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1071 }
1072
1073 void setDropInput(bool dropInput) {
1074 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1075 }
1076
1077 void setDropInputIfObscured(bool dropInputIfObscured) {
1078 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1079 }
1080
1081 void setNoInputChannel(bool noInputChannel) {
1082 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1083 }
1084
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001085 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1086
chaviw3277faf2021-05-19 16:45:23 -05001087 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001088
Bernardo Rufino7393d172021-02-26 13:56:11 +00001089 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1090
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001091 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001092 mInfo.frameLeft = frame.left;
1093 mInfo.frameTop = frame.top;
1094 mInfo.frameRight = frame.right;
1095 mInfo.frameBottom = frame.bottom;
1096 mInfo.touchableRegion.clear();
1097 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001098
1099 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1100 ui::Transform translate;
1101 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1102 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001103 }
1104
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001105 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1106
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001107 void setIsWallpaper(bool isWallpaper) {
1108 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1109 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001110
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001111 void setDupTouchToWallpaper(bool hasWallpaper) {
1112 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1113 }
chaviwd1c23182019-12-20 18:44:56 -08001114
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001115 void setTrustedOverlay(bool trustedOverlay) {
1116 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1117 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001118
chaviw9eaa22c2020-07-01 16:21:27 -07001119 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1120 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1121 }
1122
1123 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001124
yunho.shinf4a80b82020-11-16 21:13:57 +09001125 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1126
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001127 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1128 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1129 expectedFlags);
1130 }
1131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001132 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1133 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1134 }
1135
Svet Ganov5d3bc372020-01-26 23:11:07 -08001136 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001137 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001138 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1139 expectedFlags);
1140 }
1141
1142 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001143 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001144 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1145 expectedFlags);
1146 }
1147
1148 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001149 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001150 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1151 }
1152
1153 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1154 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001155 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1156 expectedFlags);
1157 }
1158
Svet Ganov5d3bc372020-01-26 23:11:07 -08001159 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001160 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1161 int32_t expectedFlags = 0) {
1162 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1163 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001164 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1165 }
1166
1167 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001168 int32_t expectedFlags = 0) {
1169 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1170 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001171 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1172 }
1173
1174 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001175 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001176 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1177 expectedFlags);
1178 }
1179
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001180 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1181 int32_t expectedFlags = 0) {
1182 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1183 expectedFlags);
1184 }
1185
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001186 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1187 int32_t expectedFlags = 0) {
1188 InputEvent* event = consume();
1189 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1190 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1191 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1192 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1193 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1194 }
1195
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001196 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1200 }
1201
Prabir Pradhan99987712020-11-10 18:43:05 -08001202 void consumeCaptureEvent(bool hasCapture) {
1203 ASSERT_NE(mInputReceiver, nullptr)
1204 << "Cannot consume events from a window with no receiver";
1205 mInputReceiver->consumeCaptureEvent(hasCapture);
1206 }
1207
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001208 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1209 std::optional<int32_t> expectedDisplayId,
1210 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001211 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1212 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1213 expectedFlags);
1214 }
1215
arthurhungb89ccb02020-12-30 16:19:01 +08001216 void consumeDragEvent(bool isExiting, float x, float y) {
1217 mInputReceiver->consumeDragEvent(isExiting, x, y);
1218 }
1219
Antonio Kantekf16f2832021-09-28 04:39:20 +00001220 void consumeTouchModeEvent(bool inTouchMode) {
1221 ASSERT_NE(mInputReceiver, nullptr)
1222 << "Cannot consume events from a window with no receiver";
1223 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1224 }
1225
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001227 if (mInputReceiver == nullptr) {
1228 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1229 return std::nullopt;
1230 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001231 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001232 }
1233
1234 void finishEvent(uint32_t sequenceNum) {
1235 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1236 mInputReceiver->finishEvent(sequenceNum);
1237 }
1238
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001239 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1240 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1241 mInputReceiver->sendTimeline(inputEventId, timeline);
1242 }
1243
chaviwaf87b3e2019-10-01 16:59:28 -07001244 InputEvent* consume() {
1245 if (mInputReceiver == nullptr) {
1246 return nullptr;
1247 }
1248 return mInputReceiver->consume();
1249 }
1250
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001251 MotionEvent* consumeMotion() {
1252 InputEvent* event = consume();
1253 if (event == nullptr) {
1254 ADD_FAILURE() << "Consume failed : no event";
1255 return nullptr;
1256 }
1257 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1258 ADD_FAILURE() << "Instead of motion event, got "
1259 << inputEventTypeToString(event->getType());
1260 return nullptr;
1261 }
1262 return static_cast<MotionEvent*>(event);
1263 }
1264
Arthur Hungb92218b2018-08-14 12:00:21 +08001265 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001266 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001267 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001268 return; // Can't receive events if the window does not have input channel
1269 }
1270 ASSERT_NE(nullptr, mInputReceiver)
1271 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001272 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001273 }
1274
chaviwaf87b3e2019-10-01 16:59:28 -07001275 sp<IBinder> getToken() { return mInfo.token; }
1276
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001277 const std::string& getName() { return mName; }
1278
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001279 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1280 mInfo.ownerPid = ownerPid;
1281 mInfo.ownerUid = ownerUid;
1282 }
1283
Prabir Pradhanedd96402022-02-15 01:46:16 -08001284 int32_t getPid() const { return mInfo.ownerPid; }
1285
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001286 void destroyReceiver() { mInputReceiver = nullptr; }
1287
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001288 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1289
chaviwd1c23182019-12-20 18:44:56 -08001290private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001291 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001292 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001293 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001294};
1295
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001296std::atomic<int32_t> FakeWindowHandle::sId{1};
1297
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001298static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001299 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001300 int32_t displayId = ADISPLAY_ID_NONE,
1301 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001302 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001303 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1304 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001305 KeyEvent event;
1306 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1307
1308 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001309 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001310 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1311 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001312
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001313 if (!allowKeyRepeat) {
1314 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1315 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001316 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001317 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001318}
1319
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001320static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001321 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001322 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1323}
1324
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001325// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1326// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1327// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001328static InputEventInjectionResult injectKeyDownNoRepeat(
1329 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001330 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1331 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1332 /* allowKeyRepeat */ false);
1333}
1334
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001335static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001336 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001337 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1338}
1339
Garfield Tandf26e862020-07-01 20:18:19 -07001340class PointerBuilder {
1341public:
1342 PointerBuilder(int32_t id, int32_t toolType) {
1343 mProperties.clear();
1344 mProperties.id = id;
1345 mProperties.toolType = toolType;
1346 mCoords.clear();
1347 }
1348
1349 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1350
1351 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1352
1353 PointerBuilder& axis(int32_t axis, float value) {
1354 mCoords.setAxisValue(axis, value);
1355 return *this;
1356 }
1357
1358 PointerProperties buildProperties() const { return mProperties; }
1359
1360 PointerCoords buildCoords() const { return mCoords; }
1361
1362private:
1363 PointerProperties mProperties;
1364 PointerCoords mCoords;
1365};
1366
1367class MotionEventBuilder {
1368public:
1369 MotionEventBuilder(int32_t action, int32_t source) {
1370 mAction = action;
1371 mSource = source;
1372 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1373 }
1374
1375 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1376 mEventTime = eventTime;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& displayId(int32_t displayId) {
1381 mDisplayId = displayId;
1382 return *this;
1383 }
1384
1385 MotionEventBuilder& actionButton(int32_t actionButton) {
1386 mActionButton = actionButton;
1387 return *this;
1388 }
1389
arthurhung6d4bed92021-03-17 11:59:33 +08001390 MotionEventBuilder& buttonState(int32_t buttonState) {
1391 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001392 return *this;
1393 }
1394
1395 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1396 mRawXCursorPosition = rawXCursorPosition;
1397 return *this;
1398 }
1399
1400 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1401 mRawYCursorPosition = rawYCursorPosition;
1402 return *this;
1403 }
1404
1405 MotionEventBuilder& pointer(PointerBuilder pointer) {
1406 mPointers.push_back(pointer);
1407 return *this;
1408 }
1409
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001410 MotionEventBuilder& addFlag(uint32_t flags) {
1411 mFlags |= flags;
1412 return *this;
1413 }
1414
Garfield Tandf26e862020-07-01 20:18:19 -07001415 MotionEvent build() {
1416 std::vector<PointerProperties> pointerProperties;
1417 std::vector<PointerCoords> pointerCoords;
1418 for (const PointerBuilder& pointer : mPointers) {
1419 pointerProperties.push_back(pointer.buildProperties());
1420 pointerCoords.push_back(pointer.buildCoords());
1421 }
1422
1423 // Set mouse cursor position for the most common cases to avoid boilerplate.
1424 if (mSource == AINPUT_SOURCE_MOUSE &&
1425 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1426 mPointers.size() == 1) {
1427 mRawXCursorPosition = pointerCoords[0].getX();
1428 mRawYCursorPosition = pointerCoords[0].getY();
1429 }
1430
1431 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001432 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001433 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001434 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001435 mButtonState, MotionClassification::NONE, identityTransform,
1436 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001437 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1438 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001439
1440 return event;
1441 }
1442
1443private:
1444 int32_t mAction;
1445 int32_t mSource;
1446 nsecs_t mEventTime;
1447 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1448 int32_t mActionButton{0};
1449 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001450 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001451 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1452 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1453
1454 std::vector<PointerBuilder> mPointers;
1455};
1456
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001457static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001458 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001459 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001460 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1461 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1462 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1463 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001464}
1465
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001467 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001468 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001469 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001470 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1471 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001473 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1474 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001475 MotionEvent event = MotionEventBuilder(action, source)
1476 .displayId(displayId)
1477 .eventTime(eventTime)
1478 .rawXCursorPosition(cursorPosition.x)
1479 .rawYCursorPosition(cursorPosition.y)
1480 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1481 .x(position.x)
1482 .y(position.y))
1483 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001484
1485 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001486 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1487 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001488}
1489
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001490static InputEventInjectionResult injectMotionDown(
1491 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1492 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001493 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001494}
1495
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001496static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 int32_t source, int32_t displayId,
1498 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001499 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001500}
1501
Jackal Guof9696682018-10-05 12:23:23 +08001502static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1503 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1504 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001505 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1506 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1507 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001508
1509 return args;
1510}
1511
chaviwd1c23182019-12-20 18:44:56 -08001512static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1513 const std::vector<PointF>& points) {
1514 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001515 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1516 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1517 }
1518
chaviwd1c23182019-12-20 18:44:56 -08001519 PointerProperties pointerProperties[pointerCount];
1520 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001521
chaviwd1c23182019-12-20 18:44:56 -08001522 for (size_t i = 0; i < pointerCount; i++) {
1523 pointerProperties[i].clear();
1524 pointerProperties[i].id = i;
1525 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001526
chaviwd1c23182019-12-20 18:44:56 -08001527 pointerCoords[i].clear();
1528 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1529 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1530 }
Jackal Guof9696682018-10-05 12:23:23 +08001531
1532 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1533 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001534 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001535 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1536 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001537 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1538 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001539 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1540 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001541
1542 return args;
1543}
1544
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001545static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1546 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1547}
1548
chaviwd1c23182019-12-20 18:44:56 -08001549static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1550 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1551}
1552
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1554 const PointerCaptureRequest& request) {
1555 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001556}
1557
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001558/**
1559 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1560 * broken channel.
1561 */
1562TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1563 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1564 sp<FakeWindowHandle> window =
1565 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1566 ADISPLAY_ID_DEFAULT);
1567
1568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1569
1570 // Window closes its channel, but the window remains.
1571 window->destroyReceiver();
1572 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1573}
1574
Arthur Hungb92218b2018-08-14 12:00:21 +08001575TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001577 sp<FakeWindowHandle> window =
1578 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001579
Arthur Hung72d8dc32020-03-28 00:48:39 +00001580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1582 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001584
1585 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001586 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001587}
1588
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001589TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1590 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1591 sp<FakeWindowHandle> window =
1592 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1593
1594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1595 // Inject a MotionEvent to an unknown display.
1596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1597 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1598 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1599
1600 // Window should receive motion event.
1601 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1602}
1603
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001604/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001605 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606 * This test serves as a sanity check for the next test, where setInputWindows is
1607 * called twice.
1608 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001609TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001610 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001611 sp<FakeWindowHandle> window =
1612 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1613 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001614
1615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1618 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001620
1621 // Window should receive motion event.
1622 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1623}
1624
1625/**
1626 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001627 */
1628TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001630 sp<FakeWindowHandle> window =
1631 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1632 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001633
1634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001637 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1638 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001640
1641 // Window should receive motion event.
1642 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1643}
1644
Arthur Hungb92218b2018-08-14 12:00:21 +08001645// The foreground window should receive the first touch down event.
1646TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001647 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001648 sp<FakeWindowHandle> windowTop =
1649 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1650 sp<FakeWindowHandle> windowSecond =
1651 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001652
Arthur Hung72d8dc32020-03-28 00:48:39 +00001653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1655 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001657
1658 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001659 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001660 windowSecond->assertNoEvents();
1661}
1662
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001663/**
1664 * Two windows: A top window, and a wallpaper behind the window.
1665 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1666 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001667 * 1. foregroundWindow <-- dup touch to wallpaper
1668 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001669 */
1670TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1671 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1672 sp<FakeWindowHandle> foregroundWindow =
1673 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001674 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001675 sp<FakeWindowHandle> wallpaperWindow =
1676 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001677 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001678
1679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1681 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1682 {100, 200}))
1683 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1684
1685 // Both foreground window and its wallpaper should receive the touch down
1686 foregroundWindow->consumeMotionDown();
1687 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1688
1689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1690 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1691 ADISPLAY_ID_DEFAULT, {110, 200}))
1692 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1693
1694 foregroundWindow->consumeMotionMove();
1695 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1696
1697 // Now the foreground window goes away, but the wallpaper stays
1698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1699 foregroundWindow->consumeMotionCancel();
1700 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1701 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1702}
1703
1704/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001705 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1706 * with the following differences:
1707 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1708 * clean up the connection.
1709 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1710 * Ensure that there's no crash in the dispatcher.
1711 */
1712TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1713 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1714 sp<FakeWindowHandle> foregroundWindow =
1715 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001716 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001717 sp<FakeWindowHandle> wallpaperWindow =
1718 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001719 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001720
1721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1724 {100, 200}))
1725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1726
1727 // Both foreground window and its wallpaper should receive the touch down
1728 foregroundWindow->consumeMotionDown();
1729 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1730
1731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1732 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1733 ADISPLAY_ID_DEFAULT, {110, 200}))
1734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1735
1736 foregroundWindow->consumeMotionMove();
1737 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1738
1739 // Wallpaper closes its channel, but the window remains.
1740 wallpaperWindow->destroyReceiver();
1741 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1742
1743 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1744 // is no longer valid.
1745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1746 foregroundWindow->consumeMotionCancel();
1747}
1748
Arthur Hungba703c32022-12-08 07:45:36 +00001749class ShouldSplitTouchFixture : public InputDispatcherTest,
1750 public ::testing::WithParamInterface<bool> {};
1751INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
1752 ::testing::Values(true, false));
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001753/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001754 * A single window that receives touch (on top), and a wallpaper window underneath it.
1755 * The top window gets a multitouch gesture.
1756 * Ensure that wallpaper gets the same gesture.
1757 */
Arthur Hungba703c32022-12-08 07:45:36 +00001758TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001759 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungba703c32022-12-08 07:45:36 +00001760 sp<FakeWindowHandle> foregroundWindow =
1761 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1762 foregroundWindow->setDupTouchToWallpaper(true);
1763 foregroundWindow->setPreventSplitting(GetParam());
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001764
1765 sp<FakeWindowHandle> wallpaperWindow =
1766 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001767 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001768
Arthur Hungba703c32022-12-08 07:45:36 +00001769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001770
1771 // Touch down on top window
1772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1773 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1774 {100, 100}))
1775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1776
1777 // Both top window and its wallpaper should receive the touch down
Arthur Hungba703c32022-12-08 07:45:36 +00001778 foregroundWindow->consumeMotionDown();
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001779 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1780
1781 // Second finger down on the top window
1782 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001783 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001784 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1785 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1786 .x(100)
1787 .y(100))
1788 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1789 .x(150)
1790 .y(150))
1791 .build();
1792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1793 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1794 InputEventInjectionSync::WAIT_FOR_RESULT))
1795 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1796
Arthur Hungba703c32022-12-08 07:45:36 +00001797 foregroundWindow->consumeMotionPointerDown(1 /* pointerIndex */);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001798 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1799 expectedWallpaperFlags);
Arthur Hungba703c32022-12-08 07:45:36 +00001800
1801 const MotionEvent secondFingerUpEvent =
1802 MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
1803 .displayId(ADISPLAY_ID_DEFAULT)
1804 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1805 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1806 .x(100)
1807 .y(100))
1808 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1809 .x(150)
1810 .y(150))
1811 .build();
1812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1813 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1814 InputEventInjectionSync::WAIT_FOR_RESULT))
1815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1816 foregroundWindow->consumeMotionPointerUp(0);
1817 wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1818
1819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1820 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1821 {100, 100}))
1822 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1823 foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1824 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001825}
1826
1827/**
1828 * Two windows: a window on the left and window on the right.
1829 * A third window, wallpaper, is behind both windows, and spans both top windows.
1830 * The first touch down goes to the left window. A second pointer touches down on the right window.
1831 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1832 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1833 * ACTION_POINTER_DOWN(1).
1834 */
1835TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1836 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1837 sp<FakeWindowHandle> leftWindow =
1838 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1839 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001840 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001841
1842 sp<FakeWindowHandle> rightWindow =
1843 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1844 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001845 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001846
1847 sp<FakeWindowHandle> wallpaperWindow =
1848 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1849 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001850 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001851
1852 mDispatcher->setInputWindows(
1853 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1854
1855 // Touch down on left window
1856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1857 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1858 {100, 100}))
1859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1860
1861 // Both foreground window and its wallpaper should receive the touch down
1862 leftWindow->consumeMotionDown();
1863 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1864
1865 // Second finger down on the right window
1866 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001867 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001868 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1869 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1870 .x(100)
1871 .y(100))
1872 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1873 .x(300)
1874 .y(100))
1875 .build();
1876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1877 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1878 InputEventInjectionSync::WAIT_FOR_RESULT))
1879 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1880
1881 leftWindow->consumeMotionMove();
1882 // Since the touch is split, right window gets ACTION_DOWN
1883 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1884 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1885 expectedWallpaperFlags);
1886
1887 // Now, leftWindow, which received the first finger, disappears.
1888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1889 leftWindow->consumeMotionCancel();
1890 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1891 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1892
1893 // The pointer that's still down on the right window moves, and goes to the right window only.
1894 // As far as the dispatcher's concerned though, both pointers are still present.
1895 const MotionEvent secondFingerMoveEvent =
1896 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1897 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1898 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1899 .x(100)
1900 .y(100))
1901 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1902 .x(310)
1903 .y(110))
1904 .build();
1905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1906 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1907 InputEventInjectionSync::WAIT_FOR_RESULT));
1908 rightWindow->consumeMotionMove();
1909
1910 leftWindow->assertNoEvents();
1911 rightWindow->assertNoEvents();
1912 wallpaperWindow->assertNoEvents();
1913}
1914
Arthur Hungba703c32022-12-08 07:45:36 +00001915/**
1916 * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
1917 * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
1918 * The right window should receive ACTION_DOWN.
1919 */
1920TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
Arthur Hung69d75572022-11-15 03:30:48 +00001921 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hungba703c32022-12-08 07:45:36 +00001922 sp<FakeWindowHandle> leftWindow =
1923 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1924 leftWindow->setFrame(Rect(0, 0, 200, 200));
1925 leftWindow->setDupTouchToWallpaper(true);
1926 leftWindow->setSlippery(true);
1927
1928 sp<FakeWindowHandle> rightWindow =
1929 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1930 rightWindow->setFrame(Rect(200, 0, 400, 200));
Arthur Hung69d75572022-11-15 03:30:48 +00001931
1932 sp<FakeWindowHandle> wallpaperWindow =
Arthur Hungba703c32022-12-08 07:45:36 +00001933 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Arthur Hung69d75572022-11-15 03:30:48 +00001934 wallpaperWindow->setIsWallpaper(true);
Arthur Hung69d75572022-11-15 03:30:48 +00001935
Arthur Hungba703c32022-12-08 07:45:36 +00001936 mDispatcher->setInputWindows(
1937 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
Arthur Hung69d75572022-11-15 03:30:48 +00001938
Arthur Hungba703c32022-12-08 07:45:36 +00001939 // Touch down on left window
Arthur Hung69d75572022-11-15 03:30:48 +00001940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1941 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Arthur Hungba703c32022-12-08 07:45:36 +00001942 {100, 100}))
Arthur Hung69d75572022-11-15 03:30:48 +00001943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungba703c32022-12-08 07:45:36 +00001944
1945 // Both foreground window and its wallpaper should receive the touch down
1946 leftWindow->consumeMotionDown();
Arthur Hung69d75572022-11-15 03:30:48 +00001947 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1948
Arthur Hungba703c32022-12-08 07:45:36 +00001949 // Move to right window, the left window should receive cancel.
Arthur Hung69d75572022-11-15 03:30:48 +00001950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Arthur Hungba703c32022-12-08 07:45:36 +00001951 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1952 ADISPLAY_ID_DEFAULT, {201, 100}))
Arthur Hung69d75572022-11-15 03:30:48 +00001953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1954
Arthur Hungba703c32022-12-08 07:45:36 +00001955 leftWindow->consumeMotionCancel();
1956 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1957 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Arthur Hung69d75572022-11-15 03:30:48 +00001958}
1959
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001960/**
1961 * On the display, have a single window, and also an area where there's no window.
1962 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1963 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1964 */
1965TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1967 sp<FakeWindowHandle> window =
1968 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1969
1970 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1971 NotifyMotionArgs args;
1972
1973 // Touch down on the empty space
1974 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1975
1976 mDispatcher->waitForIdle();
1977 window->assertNoEvents();
1978
1979 // Now touch down on the window with another pointer
1980 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1981 mDispatcher->waitForIdle();
1982 window->consumeMotionDown();
1983}
1984
1985/**
1986 * Same test as above, but instead of touching the empty space, the first touch goes to
1987 * non-touchable window.
1988 */
1989TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1990 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1991 sp<FakeWindowHandle> window1 =
1992 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1993 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1994 window1->setTouchable(false);
1995 sp<FakeWindowHandle> window2 =
1996 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1997 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1998
1999 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
2000
2001 NotifyMotionArgs args;
2002 // Touch down on the non-touchable window
2003 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
2004
2005 mDispatcher->waitForIdle();
2006 window1->assertNoEvents();
2007 window2->assertNoEvents();
2008
2009 // Now touch down on the window with another pointer
2010 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
2011 mDispatcher->waitForIdle();
2012 window2->consumeMotionDown();
2013}
2014
Garfield Tandf26e862020-07-01 20:18:19 -07002015TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002016 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002017 sp<FakeWindowHandle> windowLeft =
2018 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2019 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002020 sp<FakeWindowHandle> windowRight =
2021 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2022 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002023
2024 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2025
2026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2027
2028 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002030 injectMotionEvent(mDispatcher,
2031 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2032 AINPUT_SOURCE_MOUSE)
2033 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2034 .x(900)
2035 .y(400))
2036 .build()));
2037 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2038 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2039 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2040 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2041
2042 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002044 injectMotionEvent(mDispatcher,
2045 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2046 AINPUT_SOURCE_MOUSE)
2047 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2048 .x(300)
2049 .y(400))
2050 .build()));
2051 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2052 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2053 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2054 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2055 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2056 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2057
2058 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002060 injectMotionEvent(mDispatcher,
2061 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2062 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2063 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2064 .x(300)
2065 .y(400))
2066 .build()));
2067 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2068
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002070 injectMotionEvent(mDispatcher,
2071 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2072 AINPUT_SOURCE_MOUSE)
2073 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2074 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2075 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2076 .x(300)
2077 .y(400))
2078 .build()));
2079 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2080 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002083 injectMotionEvent(mDispatcher,
2084 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2085 AINPUT_SOURCE_MOUSE)
2086 .buttonState(0)
2087 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2088 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2089 .x(300)
2090 .y(400))
2091 .build()));
2092 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2093 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2094
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002096 injectMotionEvent(mDispatcher,
2097 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2098 .buttonState(0)
2099 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2100 .x(300)
2101 .y(400))
2102 .build()));
2103 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2104
2105 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002107 injectMotionEvent(mDispatcher,
2108 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2109 AINPUT_SOURCE_MOUSE)
2110 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2111 .x(900)
2112 .y(400))
2113 .build()));
2114 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2115 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2116 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2117 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2118 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2119 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2120}
2121
2122// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2123// directly in this test.
2124TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002126 sp<FakeWindowHandle> window =
2127 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2128 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002129
2130 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2131
2132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2133
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002135 injectMotionEvent(mDispatcher,
2136 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2137 AINPUT_SOURCE_MOUSE)
2138 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2139 .x(300)
2140 .y(400))
2141 .build()));
2142 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2143 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2144
2145 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002146 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002147 injectMotionEvent(mDispatcher,
2148 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2149 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2150 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2151 .x(300)
2152 .y(400))
2153 .build()));
2154 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2155
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002157 injectMotionEvent(mDispatcher,
2158 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2159 AINPUT_SOURCE_MOUSE)
2160 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2161 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2162 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2163 .x(300)
2164 .y(400))
2165 .build()));
2166 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2167 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2168
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002169 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002170 injectMotionEvent(mDispatcher,
2171 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2172 AINPUT_SOURCE_MOUSE)
2173 .buttonState(0)
2174 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2175 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2176 .x(300)
2177 .y(400))
2178 .build()));
2179 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2180 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2181
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002183 injectMotionEvent(mDispatcher,
2184 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2185 .buttonState(0)
2186 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2187 .x(300)
2188 .y(400))
2189 .build()));
2190 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2191
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002193 injectMotionEvent(mDispatcher,
2194 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2195 AINPUT_SOURCE_MOUSE)
2196 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2197 .x(300)
2198 .y(400))
2199 .build()));
2200 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2201 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2202}
2203
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02002204TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2205 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2206 sp<FakeWindowHandle> windowDefaultDisplay =
2207 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2208 ADISPLAY_ID_DEFAULT);
2209 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2210 sp<FakeWindowHandle> windowSecondDisplay =
2211 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2212 SECOND_DISPLAY_ID);
2213 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2214
2215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2216 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2217
2218 // Set cursor position in window in default display and check that hover enter and move
2219 // events are generated.
2220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2221 injectMotionEvent(mDispatcher,
2222 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2223 AINPUT_SOURCE_MOUSE)
2224 .displayId(ADISPLAY_ID_DEFAULT)
2225 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2226 .x(300)
2227 .y(600))
2228 .build()));
2229 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2230 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2231 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2232 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2233
2234 // Remove all windows in secondary display and check that no event happens on window in
2235 // primary display.
2236 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
2237 windowDefaultDisplay->assertNoEvents();
2238
2239 // Move cursor position in window in default display and check that only hover move
2240 // event is generated and not hover enter event.
2241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2242 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2244 injectMotionEvent(mDispatcher,
2245 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2246 AINPUT_SOURCE_MOUSE)
2247 .displayId(ADISPLAY_ID_DEFAULT)
2248 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2249 .x(400)
2250 .y(700))
2251 .build()));
2252 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2253 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2254 windowDefaultDisplay->assertNoEvents();
2255}
2256
Garfield Tan00f511d2019-06-12 16:55:40 -07002257TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002258 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002259
2260 sp<FakeWindowHandle> windowLeft =
2261 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2262 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002263 sp<FakeWindowHandle> windowRight =
2264 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2265 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002266
2267 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2268
Arthur Hung72d8dc32020-03-28 00:48:39 +00002269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002270
2271 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2272 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002273 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002274 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002275 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002276 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002277 windowRight->assertNoEvents();
2278}
2279
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002280TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002282 sp<FakeWindowHandle> window =
2283 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002284 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002285
Arthur Hung72d8dc32020-03-28 00:48:39 +00002286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002287 setFocusedWindow(window);
2288
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002289 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002290
2291 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2292 mDispatcher->notifyKey(&keyArgs);
2293
2294 // Window should receive key down event.
2295 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2296
2297 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2298 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002299 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002300 mDispatcher->notifyDeviceReset(&args);
2301 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2302 AKEY_EVENT_FLAG_CANCELED);
2303}
2304
2305TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002306 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002307 sp<FakeWindowHandle> window =
2308 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2309
Arthur Hung72d8dc32020-03-28 00:48:39 +00002310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002311
2312 NotifyMotionArgs motionArgs =
2313 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2314 ADISPLAY_ID_DEFAULT);
2315 mDispatcher->notifyMotion(&motionArgs);
2316
2317 // Window should receive motion down event.
2318 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2319
2320 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2321 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002322 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002323 mDispatcher->notifyDeviceReset(&args);
2324 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2325 0 /*expectedFlags*/);
2326}
2327
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002328TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2330 sp<FakeWindowHandle> window =
2331 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2332 window->setFocusable(true);
2333
2334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2335 setFocusedWindow(window);
2336
2337 window->consumeFocusEvent(true);
2338
2339 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2340 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2341 const nsecs_t injectTime = keyArgs.eventTime;
2342 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2343 mDispatcher->notifyKey(&keyArgs);
2344 // The dispatching time should be always greater than or equal to intercept key timeout.
2345 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2346 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2347 std::chrono::nanoseconds(interceptKeyTimeout).count());
2348}
2349
2350TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2351 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2352 sp<FakeWindowHandle> window =
2353 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2354 window->setFocusable(true);
2355
2356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2357 setFocusedWindow(window);
2358
2359 window->consumeFocusEvent(true);
2360
2361 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2362 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2363 mFakePolicy->setInterceptKeyTimeout(150ms);
2364 mDispatcher->notifyKey(&keyDown);
2365 mDispatcher->notifyKey(&keyUp);
2366
2367 // Window should receive key event immediately when same key up.
2368 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2369 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2370}
2371
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002372/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002373 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2374 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2375 * ACTION_OUTSIDE event is sent per gesture.
2376 */
2377TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2378 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2379 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2380 sp<FakeWindowHandle> window =
2381 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2382 window->setWatchOutsideTouch(true);
2383 window->setFrame(Rect{0, 0, 100, 100});
2384 sp<FakeWindowHandle> secondWindow =
2385 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2386 secondWindow->setFrame(Rect{100, 100, 200, 200});
2387 sp<FakeWindowHandle> thirdWindow =
2388 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2389 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2391
2392 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2393 NotifyMotionArgs motionArgs =
2394 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2395 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2396 mDispatcher->notifyMotion(&motionArgs);
2397 window->assertNoEvents();
2398 secondWindow->assertNoEvents();
2399
2400 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2401 // Now, `window` should get ACTION_OUTSIDE.
2402 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2403 {PointF{-10, -10}, PointF{105, 105}});
2404 mDispatcher->notifyMotion(&motionArgs);
2405 window->consumeMotionOutside();
2406 secondWindow->consumeMotionDown();
2407 thirdWindow->assertNoEvents();
2408
2409 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2410 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2411 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2412 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2413 mDispatcher->notifyMotion(&motionArgs);
2414 window->assertNoEvents();
2415 secondWindow->consumeMotionMove();
2416 thirdWindow->consumeMotionDown();
2417}
2418
Prabir Pradhan73fe4812022-07-22 20:22:18 +00002419TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2420 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2421 sp<FakeWindowHandle> window =
2422 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2423 window->setFocusable(true);
2424
2425 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2426 setFocusedWindow(window);
2427
2428 window->consumeFocusEvent(true);
2429
2430 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2431 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2432 mDispatcher->notifyKey(&keyDown);
2433 mDispatcher->notifyKey(&keyUp);
2434
2435 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2436 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2437
2438 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2439 mDispatcher->onWindowInfosChanged({}, {});
2440
2441 window->consumeFocusEvent(false);
2442
2443 mDispatcher->notifyKey(&keyDown);
2444 mDispatcher->notifyKey(&keyUp);
2445 window->assertNoEvents();
2446}
2447
Arthur Hung69d75572022-11-15 03:30:48 +00002448TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2450 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2451 "Fake Window", ADISPLAY_ID_DEFAULT);
2452 // Ensure window is non-split and have some transform.
2453 window->setPreventSplitting(true);
2454 window->setWindowOffset(20, 40);
2455 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2456
2457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2459 {50, 50}))
2460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2461 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2462
2463 const MotionEvent secondFingerDownEvent =
2464 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2465 .displayId(ADISPLAY_ID_DEFAULT)
2466 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2467 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2468 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2469 .x(-30)
2470 .y(-50))
2471 .build();
2472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2473 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2474 InputEventInjectionSync::WAIT_FOR_RESULT))
2475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2476
2477 const MotionEvent* event = window->consumeMotion();
2478 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2479 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2480 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2481 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2482 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2483}
2484
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002485/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002486 * Ensure the correct coordinate spaces are used by InputDispatcher.
2487 *
2488 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2489 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2490 * space.
2491 */
2492class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2493public:
2494 void SetUp() override {
2495 InputDispatcherTest::SetUp();
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002496 removeAllWindowsAndDisplays();
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002497 }
2498
2499 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2500 gui::DisplayInfo info;
2501 info.displayId = displayId;
2502 info.transform = transform;
2503 mDisplayInfos.push_back(std::move(info));
2504 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2505 }
2506
2507 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2508 mWindowInfos.push_back(*windowHandle->getInfo());
2509 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2510 }
2511
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002512 void removeAllWindowsAndDisplays() {
2513 mDisplayInfos.clear();
2514 mWindowInfos.clear();
2515 }
2516
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002517 // Set up a test scenario where the display has a scaled projection and there are two windows
2518 // on the display.
2519 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2520 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2521 // respectively.
2522 ui::Transform displayTransform;
2523 displayTransform.set(2, 0, 0, 4);
2524 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2525
2526 std::shared_ptr<FakeApplicationHandle> application =
2527 std::make_shared<FakeApplicationHandle>();
2528
2529 // Add two windows to the display. Their frames are represented in the display space.
2530 sp<FakeWindowHandle> firstWindow =
2531 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002532 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2533 addWindow(firstWindow);
2534
2535 sp<FakeWindowHandle> secondWindow =
2536 new FakeWindowHandle(application, mDispatcher, "Second Window",
2537 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002538 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2539 addWindow(secondWindow);
2540 return {std::move(firstWindow), std::move(secondWindow)};
2541 }
2542
2543private:
2544 std::vector<gui::DisplayInfo> mDisplayInfos;
2545 std::vector<gui::WindowInfo> mWindowInfos;
2546};
2547
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002548TEST_F(InputDispatcherDisplayProjectionTest, HitTestCoordinateSpaceConsistency) {
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002549 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2550 // Send down to the first window. The point is represented in the display space. The point is
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002551 // selected so that if the hit test was performed with the point and the bounds being in
2552 // different coordinate spaces, the event would end up in the incorrect window.
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002553 NotifyMotionArgs downMotionArgs =
2554 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2555 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2556 mDispatcher->notifyMotion(&downMotionArgs);
2557
2558 firstWindow->consumeMotionDown();
2559 secondWindow->assertNoEvents();
2560}
2561
2562// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2563// the event should be treated as being in the logical display space.
2564TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2565 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2566 // Send down to the first window. The point is represented in the logical display space. The
2567 // point is selected so that if the hit test was done in logical display space, then it would
2568 // end up in the incorrect window.
2569 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2570 PointF{75 * 2, 55 * 4});
2571
2572 firstWindow->consumeMotionDown();
2573 secondWindow->assertNoEvents();
2574}
2575
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002576// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2577// event should be treated as being in the logical display space.
2578TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2579 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2580
2581 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2582 ui::Transform injectedEventTransform;
2583 injectedEventTransform.set(matrix);
2584 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2585 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2586
2587 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2588 .displayId(ADISPLAY_ID_DEFAULT)
2589 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2590 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2591 .x(untransformedPoint.x)
2592 .y(untransformedPoint.y))
2593 .build();
2594 event.transform(matrix);
2595
2596 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2597 InputEventInjectionSync::WAIT_FOR_RESULT);
2598
2599 firstWindow->consumeMotionDown();
2600 secondWindow->assertNoEvents();
2601}
2602
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002603TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2604 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2605
2606 // Send down to the second window.
2607 NotifyMotionArgs downMotionArgs =
2608 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2609 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2610 mDispatcher->notifyMotion(&downMotionArgs);
2611
2612 firstWindow->assertNoEvents();
2613 const MotionEvent* event = secondWindow->consumeMotion();
2614 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2615
2616 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2617 EXPECT_EQ(300, event->getRawX(0));
2618 EXPECT_EQ(880, event->getRawY(0));
2619
2620 // Ensure that the x and y values are in the window's coordinate space.
2621 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2622 // the logical display space. This will be the origin of the window space.
2623 EXPECT_EQ(100, event->getX(0));
2624 EXPECT_EQ(80, event->getY(0));
2625}
2626
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002627/** Ensure consistent behavior of InputDispatcher in all orientations. */
2628class InputDispatcherDisplayOrientationFixture
2629 : public InputDispatcherDisplayProjectionTest,
2630 public ::testing::WithParamInterface<ui::Rotation> {};
2631
2632// This test verifies the touchable region of a window for all rotations of the display by tapping
2633// in different locations on the display, specifically points close to the four corners of a
2634// window.
2635TEST_P(InputDispatcherDisplayOrientationFixture, HitTestInDifferentOrientations) {
2636 constexpr static int32_t displayWidth = 400;
2637 constexpr static int32_t displayHeight = 800;
2638
2639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2640
2641 const auto rotation = GetParam();
2642
2643 // Set up the display with the specified rotation.
2644 const bool isRotated = rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270;
2645 const int32_t logicalDisplayWidth = isRotated ? displayHeight : displayWidth;
2646 const int32_t logicalDisplayHeight = isRotated ? displayWidth : displayHeight;
2647 const ui::Transform displayTransform(ui::Transform::toRotationFlags(rotation),
2648 logicalDisplayWidth, logicalDisplayHeight);
2649 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2650
2651 // Create a window with its bounds determined in the logical display.
2652 const Rect frameInLogicalDisplay(100, 100, 200, 300);
2653 const Rect frameInDisplay = displayTransform.inverse().transform(frameInLogicalDisplay);
2654 sp<FakeWindowHandle> window =
2655 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2656 window->setFrame(frameInDisplay, displayTransform);
2657 addWindow(window);
2658
2659 // The following points in logical display space should be inside the window.
2660 static const std::array<vec2, 4> insidePoints{
2661 {{100, 100}, {199.99, 100}, {100, 299.99}, {199.99, 299.99}}};
2662 for (const auto pointInsideWindow : insidePoints) {
2663 const vec2 p = displayTransform.inverse().transform(pointInsideWindow);
2664 const PointF pointInDisplaySpace{p.x, p.y};
2665 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2666 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2667 mDispatcher->notifyMotion(&down);
2668 window->consumeMotionDown();
2669
2670 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2671 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2672 mDispatcher->notifyMotion(&up);
2673 window->consumeMotionUp();
2674 }
2675
2676 // The following points in logical display space should be outside the window.
2677 static const std::array<vec2, 5> outsidePoints{
2678 {{200, 100}, {100, 300}, {200, 300}, {100, 99.99}, {99.99, 100}}};
2679 for (const auto pointOutsideWindow : outsidePoints) {
2680 const vec2 p = displayTransform.inverse().transform(pointOutsideWindow);
2681 const PointF pointInDisplaySpace{p.x, p.y};
2682 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2683 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2684 mDispatcher->notifyMotion(&down);
2685
2686 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2687 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2688 mDispatcher->notifyMotion(&up);
2689 }
2690 window->assertNoEvents();
2691}
2692
2693// Run the precision tests for all rotations.
2694INSTANTIATE_TEST_SUITE_P(InputDispatcherDisplayOrientationTests,
2695 InputDispatcherDisplayOrientationFixture,
2696 ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
2697 ui::ROTATION_270));
2698
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002699using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2700 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002701
2702class TransferTouchFixture : public InputDispatcherTest,
2703 public ::testing::WithParamInterface<TransferFunction> {};
2704
2705TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002706 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002707
2708 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002709 sp<FakeWindowHandle> firstWindow =
2710 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Arthur Hungba703c32022-12-08 07:45:36 +00002711 firstWindow->setDupTouchToWallpaper(true);
2712
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002713 sp<FakeWindowHandle> secondWindow =
2714 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Arthur Hungba703c32022-12-08 07:45:36 +00002715 sp<FakeWindowHandle> wallpaper =
2716 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2717 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002718 // Add the windows to the dispatcher
Arthur Hungba703c32022-12-08 07:45:36 +00002719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002720
2721 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002722 NotifyMotionArgs downMotionArgs =
2723 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2724 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002725 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungba703c32022-12-08 07:45:36 +00002726
Svet Ganov5d3bc372020-01-26 23:11:07 -08002727 // Only the first window should get the down event
2728 firstWindow->consumeMotionDown();
2729 secondWindow->assertNoEvents();
Arthur Hungba703c32022-12-08 07:45:36 +00002730 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002731
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002732 // Transfer touch to the second window
2733 TransferFunction f = GetParam();
2734 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2735 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002736 // The first window gets cancel and the second gets down
2737 firstWindow->consumeMotionCancel();
2738 secondWindow->consumeMotionDown();
Arthur Hungba703c32022-12-08 07:45:36 +00002739 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002740
2741 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002742 NotifyMotionArgs upMotionArgs =
2743 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2744 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002745 mDispatcher->notifyMotion(&upMotionArgs);
2746 // The first window gets no events and the second gets up
2747 firstWindow->assertNoEvents();
2748 secondWindow->consumeMotionUp();
Arthur Hungba703c32022-12-08 07:45:36 +00002749 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002750}
2751
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002752/**
2753 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2754 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2755 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2756 * natural to the user.
2757 * In this test, we are sending a pointer to both spy window and first window. We then try to
2758 * transfer touch to the second window. The dispatcher should identify the first window as the
2759 * one that should lose the gesture, and therefore the action should be to move the gesture from
2760 * the first window to the second.
2761 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2762 * the other API, as well.
2763 */
2764TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2765 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2766
2767 // Create a couple of windows + a spy window
2768 sp<FakeWindowHandle> spyWindow =
2769 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2770 spyWindow->setTrustedOverlay(true);
2771 spyWindow->setSpy(true);
2772 sp<FakeWindowHandle> firstWindow =
2773 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2774 sp<FakeWindowHandle> secondWindow =
2775 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2776
2777 // Add the windows to the dispatcher
2778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2779
2780 // Send down to the first window
2781 NotifyMotionArgs downMotionArgs =
2782 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2783 ADISPLAY_ID_DEFAULT);
2784 mDispatcher->notifyMotion(&downMotionArgs);
2785 // Only the first window and spy should get the down event
2786 spyWindow->consumeMotionDown();
2787 firstWindow->consumeMotionDown();
2788
2789 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2790 // if f === 'transferTouch'.
2791 TransferFunction f = GetParam();
2792 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2793 ASSERT_TRUE(success);
2794 // The first window gets cancel and the second gets down
2795 firstWindow->consumeMotionCancel();
2796 secondWindow->consumeMotionDown();
2797
2798 // Send up event to the second window
2799 NotifyMotionArgs upMotionArgs =
2800 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2801 ADISPLAY_ID_DEFAULT);
2802 mDispatcher->notifyMotion(&upMotionArgs);
2803 // The first window gets no events and the second+spy get up
2804 firstWindow->assertNoEvents();
2805 spyWindow->consumeMotionUp();
2806 secondWindow->consumeMotionUp();
2807}
2808
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002809TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002811
2812 PointF touchPoint = {10, 10};
2813
2814 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002815 sp<FakeWindowHandle> firstWindow =
2816 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002817 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002818 sp<FakeWindowHandle> secondWindow =
2819 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002820 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002821
2822 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002824
2825 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002826 NotifyMotionArgs downMotionArgs =
2827 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2828 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002829 mDispatcher->notifyMotion(&downMotionArgs);
2830 // Only the first window should get the down event
2831 firstWindow->consumeMotionDown();
2832 secondWindow->assertNoEvents();
2833
2834 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002835 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002836 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002837 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002838 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2839 // Only the first window should get the pointer down event
2840 firstWindow->consumeMotionPointerDown(1);
2841 secondWindow->assertNoEvents();
2842
2843 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002844 TransferFunction f = GetParam();
2845 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2846 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002847 // The first window gets cancel and the second gets down and pointer down
2848 firstWindow->consumeMotionCancel();
2849 secondWindow->consumeMotionDown();
2850 secondWindow->consumeMotionPointerDown(1);
2851
2852 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002853 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002854 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002855 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002856 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2857 // The first window gets nothing and the second gets pointer up
2858 firstWindow->assertNoEvents();
2859 secondWindow->consumeMotionPointerUp(1);
2860
2861 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002862 NotifyMotionArgs upMotionArgs =
2863 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2864 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002865 mDispatcher->notifyMotion(&upMotionArgs);
2866 // The first window gets nothing and the second gets up
2867 firstWindow->assertNoEvents();
2868 secondWindow->consumeMotionUp();
2869}
2870
Arthur Hungba703c32022-12-08 07:45:36 +00002871TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
2872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2873
2874 // Create a couple of windows
2875 sp<FakeWindowHandle> firstWindow =
2876 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2877 ADISPLAY_ID_DEFAULT);
2878 firstWindow->setDupTouchToWallpaper(true);
2879 sp<FakeWindowHandle> secondWindow =
2880 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2881 ADISPLAY_ID_DEFAULT);
2882 secondWindow->setDupTouchToWallpaper(true);
2883
2884 sp<FakeWindowHandle> wallpaper1 =
2885 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
2886 wallpaper1->setIsWallpaper(true);
2887
2888 sp<FakeWindowHandle> wallpaper2 =
2889 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
2890 wallpaper2->setIsWallpaper(true);
2891 // Add the windows to the dispatcher
2892 mDispatcher->setInputWindows(
2893 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
2894
2895 // Send down to the first window
2896 NotifyMotionArgs downMotionArgs =
2897 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2898 ADISPLAY_ID_DEFAULT);
2899 mDispatcher->notifyMotion(&downMotionArgs);
2900
2901 // Only the first window should get the down event
2902 firstWindow->consumeMotionDown();
2903 secondWindow->assertNoEvents();
2904 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2905 wallpaper2->assertNoEvents();
2906
2907 // Transfer touch focus to the second window
2908 TransferFunction f = GetParam();
2909 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2910 ASSERT_TRUE(success);
2911
2912 // The first window gets cancel and the second gets down
2913 firstWindow->consumeMotionCancel();
2914 secondWindow->consumeMotionDown();
2915 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2916 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2917
2918 // Send up event to the second window
2919 NotifyMotionArgs upMotionArgs =
2920 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2921 ADISPLAY_ID_DEFAULT);
2922 mDispatcher->notifyMotion(&upMotionArgs);
2923 // The first window gets no events and the second gets up
2924 firstWindow->assertNoEvents();
2925 secondWindow->consumeMotionUp();
2926 wallpaper1->assertNoEvents();
2927 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
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 =
2950 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002951 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002952
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002953 sp<FakeWindowHandle> secondWindow =
2954 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002955 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002956
2957 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002959
2960 PointF pointInFirst = {300, 200};
2961 PointF pointInSecond = {300, 600};
2962
2963 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002964 NotifyMotionArgs firstDownMotionArgs =
2965 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2966 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002967 mDispatcher->notifyMotion(&firstDownMotionArgs);
2968 // Only the first window should get the down event
2969 firstWindow->consumeMotionDown();
2970 secondWindow->assertNoEvents();
2971
2972 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002973 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002974 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002975 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002976 mDispatcher->notifyMotion(&secondDownMotionArgs);
2977 // The first window gets a move and the second a down
2978 firstWindow->consumeMotionMove();
2979 secondWindow->consumeMotionDown();
2980
2981 // Transfer touch focus to the second window
2982 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2983 // The first window gets cancel and the new gets pointer down (it already saw down)
2984 firstWindow->consumeMotionCancel();
2985 secondWindow->consumeMotionPointerDown(1);
2986
2987 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002988 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002989 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002990 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002991 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2992 // The first window gets nothing and the second gets pointer up
2993 firstWindow->assertNoEvents();
2994 secondWindow->consumeMotionPointerUp(1);
2995
2996 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002997 NotifyMotionArgs upMotionArgs =
2998 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2999 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003000 mDispatcher->notifyMotion(&upMotionArgs);
3001 // The first window gets nothing and the second gets up
3002 firstWindow->assertNoEvents();
3003 secondWindow->consumeMotionUp();
3004}
3005
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003006// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
3007// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
3008// touch is not supported, so the touch should continue on those windows and the transferred-to
3009// window should get nothing.
3010TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
3011 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3012
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003013 sp<FakeWindowHandle> firstWindow =
3014 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3015 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003016
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003017 sp<FakeWindowHandle> secondWindow =
3018 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3019 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003020
3021 // Add the windows to the dispatcher
3022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3023
3024 PointF pointInFirst = {300, 200};
3025 PointF pointInSecond = {300, 600};
3026
3027 // Send down to the first window
3028 NotifyMotionArgs firstDownMotionArgs =
3029 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3030 ADISPLAY_ID_DEFAULT, {pointInFirst});
3031 mDispatcher->notifyMotion(&firstDownMotionArgs);
3032 // Only the first window should get the down event
3033 firstWindow->consumeMotionDown();
3034 secondWindow->assertNoEvents();
3035
3036 // Send down to the second window
3037 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003038 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003039 {pointInFirst, pointInSecond});
3040 mDispatcher->notifyMotion(&secondDownMotionArgs);
3041 // The first window gets a move and the second a down
3042 firstWindow->consumeMotionMove();
3043 secondWindow->consumeMotionDown();
3044
3045 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003046 const bool transferred =
3047 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003048 // The 'transferTouch' call should not succeed, because there are 2 touched windows
3049 ASSERT_FALSE(transferred);
3050 firstWindow->assertNoEvents();
3051 secondWindow->assertNoEvents();
3052
3053 // The rest of the dispatch should proceed as normal
3054 // Send pointer up to the second window
3055 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003056 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00003057 {pointInFirst, pointInSecond});
3058 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3059 // The first window gets MOVE and the second gets pointer up
3060 firstWindow->consumeMotionMove();
3061 secondWindow->consumeMotionUp();
3062
3063 // Send up event to the first window
3064 NotifyMotionArgs upMotionArgs =
3065 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3066 ADISPLAY_ID_DEFAULT);
3067 mDispatcher->notifyMotion(&upMotionArgs);
3068 // The first window gets nothing and the second gets up
3069 firstWindow->consumeMotionUp();
3070 secondWindow->assertNoEvents();
3071}
3072
Arthur Hungabbb9d82021-09-01 14:52:30 +00003073// This case will create two windows and one mirrored window on the default display and mirror
3074// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
3075// the windows info of second display before default display.
3076TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3077 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3078 sp<FakeWindowHandle> firstWindowInPrimary =
3079 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
3080 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003081 sp<FakeWindowHandle> secondWindowInPrimary =
3082 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3083 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003084
3085 sp<FakeWindowHandle> mirrorWindowInPrimary =
3086 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3087 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003088
3089 sp<FakeWindowHandle> firstWindowInSecondary =
3090 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3091 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003092
3093 sp<FakeWindowHandle> secondWindowInSecondary =
3094 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3095 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003096
3097 // Update window info, let it find window handle of second display first.
3098 mDispatcher->setInputWindows(
3099 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3100 {ADISPLAY_ID_DEFAULT,
3101 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3102
3103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3104 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3105 {50, 50}))
3106 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3107
3108 // Window should receive motion event.
3109 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3110
3111 // Transfer touch focus
3112 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3113 secondWindowInPrimary->getToken()));
3114 // The first window gets cancel.
3115 firstWindowInPrimary->consumeMotionCancel();
3116 secondWindowInPrimary->consumeMotionDown();
3117
3118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3119 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3120 ADISPLAY_ID_DEFAULT, {150, 50}))
3121 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3122 firstWindowInPrimary->assertNoEvents();
3123 secondWindowInPrimary->consumeMotionMove();
3124
3125 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3126 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3127 {150, 50}))
3128 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3129 firstWindowInPrimary->assertNoEvents();
3130 secondWindowInPrimary->consumeMotionUp();
3131}
3132
3133// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3134// 'transferTouch' api.
3135TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3136 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3137 sp<FakeWindowHandle> firstWindowInPrimary =
3138 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
3139 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003140 sp<FakeWindowHandle> secondWindowInPrimary =
3141 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3142 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003143
3144 sp<FakeWindowHandle> mirrorWindowInPrimary =
3145 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3146 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003147
3148 sp<FakeWindowHandle> firstWindowInSecondary =
3149 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3150 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003151
3152 sp<FakeWindowHandle> secondWindowInSecondary =
3153 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3154 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003155
3156 // Update window info, let it find window handle of second display first.
3157 mDispatcher->setInputWindows(
3158 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3159 {ADISPLAY_ID_DEFAULT,
3160 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3161
3162 // Touch on second display.
3163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3164 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3165 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3166
3167 // Window should receive motion event.
3168 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3169
3170 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003171 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003172
3173 // The first window gets cancel.
3174 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3175 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3176
3177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3178 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3179 SECOND_DISPLAY_ID, {150, 50}))
3180 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3181 firstWindowInPrimary->assertNoEvents();
3182 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3183
3184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3185 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3186 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3187 firstWindowInPrimary->assertNoEvents();
3188 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3189}
3190
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003191TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003192 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003193 sp<FakeWindowHandle> window =
3194 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3195
Vishnu Nair47074b82020-08-14 11:54:47 -07003196 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003198 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003199
3200 window->consumeFocusEvent(true);
3201
3202 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3203 mDispatcher->notifyKey(&keyArgs);
3204
3205 // Window should receive key down event.
3206 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3207}
3208
3209TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003210 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003211 sp<FakeWindowHandle> window =
3212 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3213
Arthur Hung72d8dc32020-03-28 00:48:39 +00003214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003215
3216 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3217 mDispatcher->notifyKey(&keyArgs);
3218 mDispatcher->waitForIdle();
3219
3220 window->assertNoEvents();
3221}
3222
3223// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3224TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003226 sp<FakeWindowHandle> window =
3227 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3228
Arthur Hung72d8dc32020-03-28 00:48:39 +00003229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003230
3231 // Send key
3232 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3233 mDispatcher->notifyKey(&keyArgs);
3234 // Send motion
3235 NotifyMotionArgs motionArgs =
3236 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3237 ADISPLAY_ID_DEFAULT);
3238 mDispatcher->notifyMotion(&motionArgs);
3239
3240 // Window should receive only the motion event
3241 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3242 window->assertNoEvents(); // Key event or focus event will not be received
3243}
3244
arthurhungea3f4fc2020-12-21 23:18:53 +08003245TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3246 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3247
arthurhungea3f4fc2020-12-21 23:18:53 +08003248 sp<FakeWindowHandle> firstWindow =
3249 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3250 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003251
arthurhungea3f4fc2020-12-21 23:18:53 +08003252 sp<FakeWindowHandle> secondWindow =
3253 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3254 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003255
3256 // Add the windows to the dispatcher
3257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3258
3259 PointF pointInFirst = {300, 200};
3260 PointF pointInSecond = {300, 600};
3261
3262 // Send down to the first window
3263 NotifyMotionArgs firstDownMotionArgs =
3264 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3265 ADISPLAY_ID_DEFAULT, {pointInFirst});
3266 mDispatcher->notifyMotion(&firstDownMotionArgs);
3267 // Only the first window should get the down event
3268 firstWindow->consumeMotionDown();
3269 secondWindow->assertNoEvents();
3270
3271 // Send down to the second window
3272 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003273 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003274 {pointInFirst, pointInSecond});
3275 mDispatcher->notifyMotion(&secondDownMotionArgs);
3276 // The first window gets a move and the second a down
3277 firstWindow->consumeMotionMove();
3278 secondWindow->consumeMotionDown();
3279
3280 // Send pointer cancel to the second window
3281 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003282 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003283 {pointInFirst, pointInSecond});
3284 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3285 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3286 // The first window gets move and the second gets cancel.
3287 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3288 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3289
3290 // Send up event.
3291 NotifyMotionArgs upMotionArgs =
3292 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3293 ADISPLAY_ID_DEFAULT);
3294 mDispatcher->notifyMotion(&upMotionArgs);
3295 // The first window gets up and the second gets nothing.
3296 firstWindow->consumeMotionUp();
3297 secondWindow->assertNoEvents();
3298}
3299
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003300TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3301 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3302
3303 sp<FakeWindowHandle> window =
3304 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3306 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3307 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3308 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3309
3310 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3311 window->assertNoEvents();
3312 mDispatcher->waitForIdle();
3313}
3314
chaviwd1c23182019-12-20 18:44:56 -08003315class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003316public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003317 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003318 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003319 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003320 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003321 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003322 }
3323
chaviwd1c23182019-12-20 18:44:56 -08003324 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3325
3326 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3327 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3328 expectedDisplayId, expectedFlags);
3329 }
3330
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003331 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3332
3333 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3334
chaviwd1c23182019-12-20 18:44:56 -08003335 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3336 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3337 expectedDisplayId, expectedFlags);
3338 }
3339
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003340 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3341 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3342 expectedDisplayId, expectedFlags);
3343 }
3344
chaviwd1c23182019-12-20 18:44:56 -08003345 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3346 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3347 expectedDisplayId, expectedFlags);
3348 }
3349
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003350 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3351 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3352 expectedDisplayId, expectedFlags);
3353 }
3354
Arthur Hungfbfa5722021-11-16 02:45:54 +00003355 void consumeMotionPointerDown(int32_t pointerIdx) {
3356 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3357 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3358 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3359 0 /*expectedFlags*/);
3360 }
3361
Evan Rosky84f07f02021-04-16 10:42:42 -07003362 MotionEvent* consumeMotion() {
3363 InputEvent* event = mInputReceiver->consume();
3364 if (!event) {
3365 ADD_FAILURE() << "No event was produced";
3366 return nullptr;
3367 }
3368 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3369 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3370 return nullptr;
3371 }
3372 return static_cast<MotionEvent*>(event);
3373 }
3374
chaviwd1c23182019-12-20 18:44:56 -08003375 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3376
3377private:
3378 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003379};
3380
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003381using InputDispatcherMonitorTest = InputDispatcherTest;
3382
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003383/**
3384 * Two entities that receive touch: A window, and a global monitor.
3385 * The touch goes to the window, and then the window disappears.
3386 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3387 * for the monitor, as well.
3388 * 1. foregroundWindow
3389 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3390 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003391TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003392 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3393 sp<FakeWindowHandle> window =
3394 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3395
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003396 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003397
3398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3400 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3401 {100, 200}))
3402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3403
3404 // Both the foreground window and the global monitor should receive the touch down
3405 window->consumeMotionDown();
3406 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3407
3408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3409 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3410 ADISPLAY_ID_DEFAULT, {110, 200}))
3411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3412
3413 window->consumeMotionMove();
3414 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3415
3416 // Now the foreground window goes away
3417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3418 window->consumeMotionCancel();
3419 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3420
3421 // If more events come in, there will be no more foreground window to send them to. This will
3422 // cause a cancel for the monitor, as well.
3423 ASSERT_EQ(InputEventInjectionResult::FAILED,
3424 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3425 ADISPLAY_ID_DEFAULT, {120, 200}))
3426 << "Injection should fail because the window was removed";
3427 window->assertNoEvents();
3428 // Global monitor now gets the cancel
3429 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3430}
3431
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003432TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003433 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003434 sp<FakeWindowHandle> window =
3435 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003437
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003438 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003441 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003442 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003443 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003444 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003445}
3446
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003447TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3448 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003449
Chris Yea209fde2020-07-22 13:54:51 -07003450 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003451 sp<FakeWindowHandle> window =
3452 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003454
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003456 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003458 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003459 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003460
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003461 // Pilfer pointers from the monitor.
3462 // This should not do anything and the window should continue to receive events.
3463 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003464
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003466 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3467 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003468 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003469
3470 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3471 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003472}
3473
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003474TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003475 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3476 sp<FakeWindowHandle> window =
3477 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3479 window->setWindowOffset(20, 40);
3480 window->setWindowTransform(0, 1, -1, 0);
3481
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003482 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003483
3484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3486 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3487 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3488 MotionEvent* event = monitor.consumeMotion();
3489 // Even though window has transform, gesture monitor must not.
3490 ASSERT_EQ(ui::Transform(), event->getTransform());
3491}
3492
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003493TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003494 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003495 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003496
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003497 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003499 << "Injection should fail if there is a monitor, but no touchable window";
3500 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003501}
3502
chaviw81e2bb92019-12-18 15:03:51 -08003503TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003504 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003505 sp<FakeWindowHandle> window =
3506 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3507
Arthur Hung72d8dc32020-03-28 00:48:39 +00003508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003509
3510 NotifyMotionArgs motionArgs =
3511 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3512 ADISPLAY_ID_DEFAULT);
3513
3514 mDispatcher->notifyMotion(&motionArgs);
3515 // Window should receive motion down event.
3516 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3517
3518 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003519 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003520 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3521 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3522 motionArgs.pointerCoords[0].getX() - 10);
3523
3524 mDispatcher->notifyMotion(&motionArgs);
3525 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3526 0 /*expectedFlags*/);
3527}
3528
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003529/**
3530 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3531 * the device default right away. In the test scenario, we check both the default value,
3532 * and the action of enabling / disabling.
3533 */
3534TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003536 sp<FakeWindowHandle> window =
3537 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003538 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003539
3540 // Set focused application.
3541 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003542 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003543
3544 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003546 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003547 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3548
3549 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003550 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003552 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3553
3554 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003555 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3556 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003557 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003558 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003560 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003561 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3562
3563 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003564 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003566 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3567
3568 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003569 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3570 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003571 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003572 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003574 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003575 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3576
3577 window->assertNoEvents();
3578}
3579
Gang Wange9087892020-01-07 12:17:14 -05003580TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003581 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003582 sp<FakeWindowHandle> window =
3583 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3584
3585 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003586 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003587
Arthur Hung72d8dc32020-03-28 00:48:39 +00003588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003589 setFocusedWindow(window);
3590
Gang Wange9087892020-01-07 12:17:14 -05003591 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3592
3593 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3594 mDispatcher->notifyKey(&keyArgs);
3595
3596 InputEvent* event = window->consume();
3597 ASSERT_NE(event, nullptr);
3598
3599 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3600 ASSERT_NE(verified, nullptr);
3601 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3602
3603 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3604 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3605 ASSERT_EQ(keyArgs.source, verified->source);
3606 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3607
3608 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3609
3610 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003611 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003612 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003613 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3614 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3615 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3616 ASSERT_EQ(0, verifiedKey.repeatCount);
3617}
3618
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003619TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003620 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003621 sp<FakeWindowHandle> window =
3622 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3623
3624 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3625
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003626 ui::Transform transform;
3627 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3628
3629 gui::DisplayInfo displayInfo;
3630 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3631 displayInfo.transform = transform;
3632
3633 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003634
3635 NotifyMotionArgs motionArgs =
3636 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3637 ADISPLAY_ID_DEFAULT);
3638 mDispatcher->notifyMotion(&motionArgs);
3639
3640 InputEvent* event = window->consume();
3641 ASSERT_NE(event, nullptr);
3642
3643 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3644 ASSERT_NE(verified, nullptr);
3645 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3646
3647 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3648 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3649 EXPECT_EQ(motionArgs.source, verified->source);
3650 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3651
3652 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3653
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003654 const vec2 rawXY =
3655 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3656 motionArgs.pointerCoords[0].getXYValue());
3657 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3658 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003659 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003660 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003661 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003662 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3663 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3664}
3665
chaviw09c8d2d2020-08-24 15:48:26 -07003666/**
3667 * Ensure that separate calls to sign the same data are generating the same key.
3668 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3669 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3670 * tests.
3671 */
3672TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3673 KeyEvent event = getTestKeyEvent();
3674 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3675
3676 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3677 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3678 ASSERT_EQ(hmac1, hmac2);
3679}
3680
3681/**
3682 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3683 */
3684TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3685 KeyEvent event = getTestKeyEvent();
3686 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3687 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3688
3689 verifiedEvent.deviceId += 1;
3690 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3691
3692 verifiedEvent.source += 1;
3693 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3694
3695 verifiedEvent.eventTimeNanos += 1;
3696 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3697
3698 verifiedEvent.displayId += 1;
3699 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3700
3701 verifiedEvent.action += 1;
3702 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3703
3704 verifiedEvent.downTimeNanos += 1;
3705 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3706
3707 verifiedEvent.flags += 1;
3708 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3709
3710 verifiedEvent.keyCode += 1;
3711 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3712
3713 verifiedEvent.scanCode += 1;
3714 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3715
3716 verifiedEvent.metaState += 1;
3717 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3718
3719 verifiedEvent.repeatCount += 1;
3720 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3721}
3722
Vishnu Nair958da932020-08-21 17:12:37 -07003723TEST_F(InputDispatcherTest, SetFocusedWindow) {
3724 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3725 sp<FakeWindowHandle> windowTop =
3726 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3727 sp<FakeWindowHandle> windowSecond =
3728 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3729 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3730
3731 // Top window is also focusable but is not granted focus.
3732 windowTop->setFocusable(true);
3733 windowSecond->setFocusable(true);
3734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3735 setFocusedWindow(windowSecond);
3736
3737 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3739 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003740
3741 // Focused window should receive event.
3742 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3743 windowTop->assertNoEvents();
3744}
3745
3746TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3748 sp<FakeWindowHandle> window =
3749 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3750 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3751
3752 window->setFocusable(true);
3753 // Release channel for window is no longer valid.
3754 window->releaseChannel();
3755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3756 setFocusedWindow(window);
3757
3758 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003759 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3760 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003761
3762 // window channel is invalid, so it should not receive any input event.
3763 window->assertNoEvents();
3764}
3765
3766TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3767 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3768 sp<FakeWindowHandle> window =
3769 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003770 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003771 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3772
Vishnu Nair958da932020-08-21 17:12:37 -07003773 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3774 setFocusedWindow(window);
3775
3776 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003777 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3778 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003779
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003780 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003781 window->assertNoEvents();
3782}
3783
3784TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3785 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3786 sp<FakeWindowHandle> windowTop =
3787 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3788 sp<FakeWindowHandle> windowSecond =
3789 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3790 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3791
3792 windowTop->setFocusable(true);
3793 windowSecond->setFocusable(true);
3794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3795 setFocusedWindow(windowTop);
3796 windowTop->consumeFocusEvent(true);
3797
3798 setFocusedWindow(windowSecond, windowTop);
3799 windowSecond->consumeFocusEvent(true);
3800 windowTop->consumeFocusEvent(false);
3801
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3803 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003804
3805 // Focused window should receive event.
3806 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3807}
3808
3809TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3811 sp<FakeWindowHandle> windowTop =
3812 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3813 sp<FakeWindowHandle> windowSecond =
3814 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3815 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3816
3817 windowTop->setFocusable(true);
3818 windowSecond->setFocusable(true);
3819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3820 setFocusedWindow(windowSecond, windowTop);
3821
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003822 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3823 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003824
3825 // Event should be dropped.
3826 windowTop->assertNoEvents();
3827 windowSecond->assertNoEvents();
3828}
3829
3830TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3832 sp<FakeWindowHandle> window =
3833 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3834 sp<FakeWindowHandle> previousFocusedWindow =
3835 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3836 ADISPLAY_ID_DEFAULT);
3837 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3838
3839 window->setFocusable(true);
3840 previousFocusedWindow->setFocusable(true);
3841 window->setVisible(false);
3842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3843 setFocusedWindow(previousFocusedWindow);
3844 previousFocusedWindow->consumeFocusEvent(true);
3845
3846 // Requesting focus on invisible window takes focus from currently focused window.
3847 setFocusedWindow(window);
3848 previousFocusedWindow->consumeFocusEvent(false);
3849
3850 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003852 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003853 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003854
3855 // Window does not get focus event or key down.
3856 window->assertNoEvents();
3857
3858 // Window becomes visible.
3859 window->setVisible(true);
3860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3861
3862 // Window receives focus event.
3863 window->consumeFocusEvent(true);
3864 // Focused window receives key down.
3865 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3866}
3867
Vishnu Nair599f1412021-06-21 10:39:58 -07003868TEST_F(InputDispatcherTest, DisplayRemoved) {
3869 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3870 sp<FakeWindowHandle> window =
3871 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3872 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3873
3874 // window is granted focus.
3875 window->setFocusable(true);
3876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3877 setFocusedWindow(window);
3878 window->consumeFocusEvent(true);
3879
3880 // When a display is removed window loses focus.
3881 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3882 window->consumeFocusEvent(false);
3883}
3884
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003885/**
3886 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3887 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3888 * of the 'slipperyEnterWindow'.
3889 *
3890 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3891 * a way so that the touched location is no longer covered by the top window.
3892 *
3893 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3894 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3895 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3896 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3897 * with ACTION_DOWN).
3898 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3899 * window moved itself away from the touched location and had Flag::SLIPPERY.
3900 *
3901 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3902 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3903 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3904 *
3905 * In this test, we ensure that the event received by the bottom window has
3906 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3907 */
3908TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00003909 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3910 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003911
3912 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3913 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3914
3915 sp<FakeWindowHandle> slipperyExitWindow =
3916 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003917 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003918 // Make sure this one overlaps the bottom window
3919 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3920 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3921 // one. Windows with the same owner are not considered to be occluding each other.
3922 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3923
3924 sp<FakeWindowHandle> slipperyEnterWindow =
3925 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3926 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3927
3928 mDispatcher->setInputWindows(
3929 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3930
3931 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3932 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3933 ADISPLAY_ID_DEFAULT, {{50, 50}});
3934 mDispatcher->notifyMotion(&args);
3935 slipperyExitWindow->consumeMotionDown();
3936 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3937 mDispatcher->setInputWindows(
3938 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3939
3940 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3941 ADISPLAY_ID_DEFAULT, {{51, 51}});
3942 mDispatcher->notifyMotion(&args);
3943
3944 slipperyExitWindow->consumeMotionCancel();
3945
3946 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3947 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3948}
3949
Garfield Tan1c7bc862020-01-28 13:24:04 -08003950class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3951protected:
3952 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3953 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3954
Chris Yea209fde2020-07-22 13:54:51 -07003955 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003956 sp<FakeWindowHandle> mWindow;
3957
3958 virtual void SetUp() override {
3959 mFakePolicy = new FakeInputDispatcherPolicy();
3960 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003961 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003962 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3963 ASSERT_EQ(OK, mDispatcher->start());
3964
3965 setUpWindow();
3966 }
3967
3968 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003969 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003970 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3971
Vishnu Nair47074b82020-08-14 11:54:47 -07003972 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003974 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003975 mWindow->consumeFocusEvent(true);
3976 }
3977
Chris Ye2ad95392020-09-01 13:44:44 -07003978 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003979 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003980 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003981 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3982 mDispatcher->notifyKey(&keyArgs);
3983
3984 // Window should receive key down event.
3985 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3986 }
3987
3988 void expectKeyRepeatOnce(int32_t repeatCount) {
3989 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3990 InputEvent* repeatEvent = mWindow->consume();
3991 ASSERT_NE(nullptr, repeatEvent);
3992
3993 uint32_t eventType = repeatEvent->getType();
3994 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3995
3996 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3997 uint32_t eventAction = repeatKeyEvent->getAction();
3998 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3999 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
4000 }
4001
Chris Ye2ad95392020-09-01 13:44:44 -07004002 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08004003 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07004004 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08004005 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
4006 mDispatcher->notifyKey(&keyArgs);
4007
4008 // Window should receive key down event.
4009 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
4010 0 /*expectedFlags*/);
4011 }
4012};
4013
4014TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07004015 sendAndConsumeKeyDown(1 /* deviceId */);
4016 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4017 expectKeyRepeatOnce(repeatCount);
4018 }
4019}
4020
4021TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
4022 sendAndConsumeKeyDown(1 /* deviceId */);
4023 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4024 expectKeyRepeatOnce(repeatCount);
4025 }
4026 sendAndConsumeKeyDown(2 /* deviceId */);
4027 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08004028 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4029 expectKeyRepeatOnce(repeatCount);
4030 }
4031}
4032
4033TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07004034 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004035 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07004036 sendAndConsumeKeyUp(1 /* deviceId */);
4037 mWindow->assertNoEvents();
4038}
4039
4040TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
4041 sendAndConsumeKeyDown(1 /* deviceId */);
4042 expectKeyRepeatOnce(1 /*repeatCount*/);
4043 sendAndConsumeKeyDown(2 /* deviceId */);
4044 expectKeyRepeatOnce(1 /*repeatCount*/);
4045 // Stale key up from device 1.
4046 sendAndConsumeKeyUp(1 /* deviceId */);
4047 // Device 2 is still down, keep repeating
4048 expectKeyRepeatOnce(2 /*repeatCount*/);
4049 expectKeyRepeatOnce(3 /*repeatCount*/);
4050 // Device 2 key up
4051 sendAndConsumeKeyUp(2 /* deviceId */);
4052 mWindow->assertNoEvents();
4053}
4054
4055TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
4056 sendAndConsumeKeyDown(1 /* deviceId */);
4057 expectKeyRepeatOnce(1 /*repeatCount*/);
4058 sendAndConsumeKeyDown(2 /* deviceId */);
4059 expectKeyRepeatOnce(1 /*repeatCount*/);
4060 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
4061 sendAndConsumeKeyUp(2 /* deviceId */);
4062 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08004063 mWindow->assertNoEvents();
4064}
4065
liushenxiang42232912021-05-21 20:24:09 +08004066TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
4067 sendAndConsumeKeyDown(DEVICE_ID);
4068 expectKeyRepeatOnce(1 /*repeatCount*/);
4069 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
4070 mDispatcher->notifyDeviceReset(&args);
4071 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
4072 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
4073 mWindow->assertNoEvents();
4074}
4075
Garfield Tan1c7bc862020-01-28 13:24:04 -08004076TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004077 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004078 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4079 InputEvent* repeatEvent = mWindow->consume();
4080 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4081 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4082 IdGenerator::getSource(repeatEvent->getId()));
4083 }
4084}
4085
4086TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004087 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004088
4089 std::unordered_set<int32_t> idSet;
4090 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4091 InputEvent* repeatEvent = mWindow->consume();
4092 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4093 int32_t id = repeatEvent->getId();
4094 EXPECT_EQ(idSet.end(), idSet.find(id));
4095 idSet.insert(id);
4096 }
4097}
4098
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004099/* Test InputDispatcher for MultiDisplay */
4100class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4101public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004102 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004103 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004104
Chris Yea209fde2020-07-22 13:54:51 -07004105 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004106 windowInPrimary =
4107 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004108
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004109 // Set focus window for primary display, but focused display would be second one.
4110 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004111 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004113 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004114 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004115
Chris Yea209fde2020-07-22 13:54:51 -07004116 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004117 windowInSecondary =
4118 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004119 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004120 // Set focus display to second one.
4121 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4122 // Set focus window for second display.
4123 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004124 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004125 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004126 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004127 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004128 }
4129
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004130 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004131 InputDispatcherTest::TearDown();
4132
Chris Yea209fde2020-07-22 13:54:51 -07004133 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004134 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004135 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004136 windowInSecondary.clear();
4137 }
4138
4139protected:
Chris Yea209fde2020-07-22 13:54:51 -07004140 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004141 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004142 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004143 sp<FakeWindowHandle> windowInSecondary;
4144};
4145
4146TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4147 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4149 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4150 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004151 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004152 windowInSecondary->assertNoEvents();
4153
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004154 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004155 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4156 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004158 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004159 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004160}
4161
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004162TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004163 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4165 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004166 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004167 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004168 windowInSecondary->assertNoEvents();
4169
4170 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004171 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004172 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004173 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004174 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004175
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004176 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004177 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004178
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004180 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4181 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004182
4183 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004184 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004186 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004187 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004188 windowInSecondary->assertNoEvents();
4189}
4190
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004191// Test per-display input monitors for motion event.
4192TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004193 FakeMonitorReceiver monitorInPrimary =
4194 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4195 FakeMonitorReceiver monitorInSecondary =
4196 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004197
4198 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4200 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4201 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004202 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004203 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004204 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004205 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004206
4207 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4209 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4210 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004211 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004212 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004213 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004214 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004215
4216 // Test inject a non-pointer motion event.
4217 // If specific a display, it will dispatch to the focused window of particular display,
4218 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4220 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4221 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004222 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004223 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004224 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004225 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004226}
4227
4228// Test per-display input monitors for key event.
4229TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004230 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004231 FakeMonitorReceiver monitorInPrimary =
4232 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4233 FakeMonitorReceiver monitorInSecondary =
4234 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004235
4236 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4238 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004239 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004240 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004241 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004242 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004243}
4244
Vishnu Nair958da932020-08-21 17:12:37 -07004245TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4246 sp<FakeWindowHandle> secondWindowInPrimary =
4247 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
4248 secondWindowInPrimary->setFocusable(true);
4249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4250 setFocusedWindow(secondWindowInPrimary);
4251 windowInPrimary->consumeFocusEvent(false);
4252 secondWindowInPrimary->consumeFocusEvent(true);
4253
4254 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004255 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4256 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004257 windowInPrimary->assertNoEvents();
4258 windowInSecondary->assertNoEvents();
4259 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4260}
4261
Arthur Hungdfd528e2021-12-08 13:23:04 +00004262TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4263 FakeMonitorReceiver monitorInPrimary =
4264 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4265 FakeMonitorReceiver monitorInSecondary =
4266 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4267
4268 // Test touch down on primary display.
4269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4271 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4272 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4273 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4274
4275 // Test touch down on second display.
4276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4277 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4278 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4279 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4280 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4281
4282 // Trigger cancel touch.
4283 mDispatcher->cancelCurrentTouch();
4284 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4285 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4286 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4287 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4288
4289 // Test inject a move motion event, no window/monitor should receive the event.
4290 ASSERT_EQ(InputEventInjectionResult::FAILED,
4291 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4292 ADISPLAY_ID_DEFAULT, {110, 200}))
4293 << "Inject motion event should return InputEventInjectionResult::FAILED";
4294 windowInPrimary->assertNoEvents();
4295 monitorInPrimary.assertNoEvents();
4296
4297 ASSERT_EQ(InputEventInjectionResult::FAILED,
4298 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4299 SECOND_DISPLAY_ID, {110, 200}))
4300 << "Inject motion event should return InputEventInjectionResult::FAILED";
4301 windowInSecondary->assertNoEvents();
4302 monitorInSecondary.assertNoEvents();
4303}
4304
Jackal Guof9696682018-10-05 12:23:23 +08004305class InputFilterTest : public InputDispatcherTest {
4306protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004307 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4308 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004309 NotifyMotionArgs motionArgs;
4310
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004311 motionArgs =
4312 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004313 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004314 motionArgs =
4315 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004316 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004317 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004318 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004319 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4320 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004321 } else {
4322 mFakePolicy->assertFilterInputEventWasNotCalled();
4323 }
4324 }
4325
4326 void testNotifyKey(bool expectToBeFiltered) {
4327 NotifyKeyArgs keyArgs;
4328
4329 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4330 mDispatcher->notifyKey(&keyArgs);
4331 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4332 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004333 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004334
4335 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004336 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004337 } else {
4338 mFakePolicy->assertFilterInputEventWasNotCalled();
4339 }
4340 }
4341};
4342
4343// Test InputFilter for MotionEvent
4344TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4345 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4346 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4347 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4348
4349 // Enable InputFilter
4350 mDispatcher->setInputFilterEnabled(true);
4351 // Test touch on both primary and second display, and check if both events are filtered.
4352 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4353 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4354
4355 // Disable InputFilter
4356 mDispatcher->setInputFilterEnabled(false);
4357 // Test touch on both primary and second display, and check if both events aren't filtered.
4358 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4359 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4360}
4361
4362// Test InputFilter for KeyEvent
4363TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4364 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4365 testNotifyKey(/*expectToBeFiltered*/ false);
4366
4367 // Enable InputFilter
4368 mDispatcher->setInputFilterEnabled(true);
4369 // Send a key event, and check if it is filtered.
4370 testNotifyKey(/*expectToBeFiltered*/ true);
4371
4372 // Disable InputFilter
4373 mDispatcher->setInputFilterEnabled(false);
4374 // Send a key event, and check if it isn't filtered.
4375 testNotifyKey(/*expectToBeFiltered*/ false);
4376}
4377
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004378// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4379// logical display coordinate space.
4380TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4381 ui::Transform firstDisplayTransform;
4382 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4383 ui::Transform secondDisplayTransform;
4384 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4385
4386 std::vector<gui::DisplayInfo> displayInfos(2);
4387 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4388 displayInfos[0].transform = firstDisplayTransform;
4389 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4390 displayInfos[1].transform = secondDisplayTransform;
4391
4392 mDispatcher->onWindowInfosChanged({}, displayInfos);
4393
4394 // Enable InputFilter
4395 mDispatcher->setInputFilterEnabled(true);
4396
4397 // Ensure the correct transforms are used for the displays.
4398 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4399 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4400}
4401
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004402class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4403protected:
4404 virtual void SetUp() override {
4405 InputDispatcherTest::SetUp();
4406
4407 /**
4408 * We don't need to enable input filter to test the injected event policy, but we enabled it
4409 * here to make the tests more realistic, since this policy only matters when inputfilter is
4410 * on.
4411 */
4412 mDispatcher->setInputFilterEnabled(true);
4413
4414 std::shared_ptr<InputApplicationHandle> application =
4415 std::make_shared<FakeApplicationHandle>();
4416 mWindow =
4417 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4418
4419 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4420 mWindow->setFocusable(true);
4421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4422 setFocusedWindow(mWindow);
4423 mWindow->consumeFocusEvent(true);
4424 }
4425
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004426 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4427 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004428 KeyEvent event;
4429
4430 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4431 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4432 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4433 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4434 const int32_t additionalPolicyFlags =
4435 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004437 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004438 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4439 policyFlags | additionalPolicyFlags));
4440
4441 InputEvent* received = mWindow->consume();
4442 ASSERT_NE(nullptr, received);
4443 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004444 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4445 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4446 ASSERT_EQ(flags, keyEvent.getFlags());
4447 }
4448
4449 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4450 int32_t flags) {
4451 MotionEvent event;
4452 PointerProperties pointerProperties[1];
4453 PointerCoords pointerCoords[1];
4454 pointerProperties[0].clear();
4455 pointerProperties[0].id = 0;
4456 pointerCoords[0].clear();
4457 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4458 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4459
4460 ui::Transform identityTransform;
4461 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4462 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4463 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4464 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4465 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004466 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004467 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004468 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4469
4470 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004472 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004473 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4474 policyFlags | additionalPolicyFlags));
4475
4476 InputEvent* received = mWindow->consume();
4477 ASSERT_NE(nullptr, received);
4478 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4479 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4480 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4481 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004482 }
4483
4484private:
4485 sp<FakeWindowHandle> mWindow;
4486};
4487
4488TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004489 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4490 // filter. Without it, the event will no different from a regularly injected event, and the
4491 // injected device id will be overwritten.
4492 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4493 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004494}
4495
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004496TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004497 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004498 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4499 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4500}
4501
4502TEST_F(InputFilterInjectionPolicyTest,
4503 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4504 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4505 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4506 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004507}
4508
4509TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4510 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004511 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004512}
4513
chaviwfd6d3512019-03-25 13:23:49 -07004514class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004515 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004516 InputDispatcherTest::SetUp();
4517
Chris Yea209fde2020-07-22 13:54:51 -07004518 std::shared_ptr<FakeApplicationHandle> application =
4519 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004520 mUnfocusedWindow =
4521 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004522 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004523
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004524 mFocusedWindow =
4525 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4526 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004527
4528 // Set focused application.
4529 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004530 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004531
4532 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004534 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004535 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004536 }
4537
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004538 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004539 InputDispatcherTest::TearDown();
4540
4541 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004542 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004543 }
4544
4545protected:
4546 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004547 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004548 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004549};
4550
4551// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4552// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4553// the onPointerDownOutsideFocus callback.
4554TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004555 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004556 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4557 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004559 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004560
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004561 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004562 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4563}
4564
4565// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4566// DOWN on the window that doesn't have focus. Ensure no window received the
4567// onPointerDownOutsideFocus callback.
4568TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004570 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004572 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004573
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004574 ASSERT_TRUE(mDispatcher->waitForIdle());
4575 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004576}
4577
4578// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4579// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4580TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4582 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004584 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004585
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004586 ASSERT_TRUE(mDispatcher->waitForIdle());
4587 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004588}
4589
4590// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4591// DOWN on the window that already has focus. Ensure no window received the
4592// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004593TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004596 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004597 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004598 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004599
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004600 ASSERT_TRUE(mDispatcher->waitForIdle());
4601 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004602}
4603
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004604// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4605// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4606TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4607 const MotionEvent event =
4608 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4609 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4610 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4611 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4612 .build();
4613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4615 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4616
4617 ASSERT_TRUE(mDispatcher->waitForIdle());
4618 mFakePolicy->assertOnPointerDownWasNotCalled();
4619 // Ensure that the unfocused window did not receive any FOCUS events.
4620 mUnfocusedWindow->assertNoEvents();
4621}
4622
chaviwaf87b3e2019-10-01 16:59:28 -07004623// These tests ensures we can send touch events to a single client when there are multiple input
4624// windows that point to the same client token.
4625class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4626 virtual void SetUp() override {
4627 InputDispatcherTest::SetUp();
4628
Chris Yea209fde2020-07-22 13:54:51 -07004629 std::shared_ptr<FakeApplicationHandle> application =
4630 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004631 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4632 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004633 mWindow1->setFrame(Rect(0, 0, 100, 100));
4634
4635 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4636 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004637 mWindow2->setFrame(Rect(100, 100, 200, 200));
4638
Arthur Hung72d8dc32020-03-28 00:48:39 +00004639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004640 }
4641
4642protected:
4643 sp<FakeWindowHandle> mWindow1;
4644 sp<FakeWindowHandle> mWindow2;
4645
4646 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004647 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004648 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4649 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004650 }
4651
4652 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4653 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004654 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004655 InputEvent* event = window->consume();
4656
4657 ASSERT_NE(nullptr, event) << name.c_str()
4658 << ": consumer should have returned non-NULL event.";
4659
4660 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4661 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4662 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4663
4664 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004665 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004666
4667 for (size_t i = 0; i < points.size(); i++) {
4668 float expectedX = points[i].x;
4669 float expectedY = points[i].y;
4670
4671 EXPECT_EQ(expectedX, motionEvent.getX(i))
4672 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4673 << ", got " << motionEvent.getX(i);
4674 EXPECT_EQ(expectedY, motionEvent.getY(i))
4675 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4676 << ", got " << motionEvent.getY(i);
4677 }
4678 }
chaviw9eaa22c2020-07-01 16:21:27 -07004679
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004680 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004681 std::vector<PointF> expectedPoints) {
4682 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4683 ADISPLAY_ID_DEFAULT, touchedPoints);
4684 mDispatcher->notifyMotion(&motionArgs);
4685
4686 // Always consume from window1 since it's the window that has the InputReceiver
4687 consumeMotionEvent(mWindow1, action, expectedPoints);
4688 }
chaviwaf87b3e2019-10-01 16:59:28 -07004689};
4690
4691TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4692 // Touch Window 1
4693 PointF touchedPoint = {10, 10};
4694 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004695 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004696
4697 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004698 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004699
4700 // Touch Window 2
4701 touchedPoint = {150, 150};
4702 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004703 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004704}
4705
chaviw9eaa22c2020-07-01 16:21:27 -07004706TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4707 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004708 mWindow2->setWindowScale(0.5f, 0.5f);
4709
4710 // Touch Window 1
4711 PointF touchedPoint = {10, 10};
4712 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004713 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004714 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004715 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004716
4717 // Touch Window 2
4718 touchedPoint = {150, 150};
4719 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004720 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4721 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004722
chaviw9eaa22c2020-07-01 16:21:27 -07004723 // Update the transform so rotation is set
4724 mWindow2->setWindowTransform(0, -1, 1, 0);
4725 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4726 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004727}
4728
chaviw9eaa22c2020-07-01 16:21:27 -07004729TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004730 mWindow2->setWindowScale(0.5f, 0.5f);
4731
4732 // Touch Window 1
4733 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4734 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004735 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004736
4737 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004738 touchedPoints.push_back(PointF{150, 150});
4739 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004740 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004741
chaviw9eaa22c2020-07-01 16:21:27 -07004742 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004743 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004744 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004745
chaviw9eaa22c2020-07-01 16:21:27 -07004746 // Update the transform so rotation is set for Window 2
4747 mWindow2->setWindowTransform(0, -1, 1, 0);
4748 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004749 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004750}
4751
chaviw9eaa22c2020-07-01 16:21:27 -07004752TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004753 mWindow2->setWindowScale(0.5f, 0.5f);
4754
4755 // Touch Window 1
4756 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4757 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004758 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004759
4760 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004761 touchedPoints.push_back(PointF{150, 150});
4762 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004763
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004764 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004765
4766 // Move both windows
4767 touchedPoints = {{20, 20}, {175, 175}};
4768 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4769 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4770
chaviw9eaa22c2020-07-01 16:21:27 -07004771 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004772
chaviw9eaa22c2020-07-01 16:21:27 -07004773 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004774 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004775 expectedPoints.pop_back();
4776
4777 // Touch Window 2
4778 mWindow2->setWindowTransform(0, -1, 1, 0);
4779 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004780 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004781
4782 // Move both windows
4783 touchedPoints = {{20, 20}, {175, 175}};
4784 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4785 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4786
4787 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004788}
4789
4790TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4791 mWindow1->setWindowScale(0.5f, 0.5f);
4792
4793 // Touch Window 1
4794 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4795 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004796 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004797
4798 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004799 touchedPoints.push_back(PointF{150, 150});
4800 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004801
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004802 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004803
4804 // Move both windows
4805 touchedPoints = {{20, 20}, {175, 175}};
4806 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4807 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4808
chaviw9eaa22c2020-07-01 16:21:27 -07004809 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004810}
4811
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004812class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4813 virtual void SetUp() override {
4814 InputDispatcherTest::SetUp();
4815
Chris Yea209fde2020-07-22 13:54:51 -07004816 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004817 mApplication->setDispatchingTimeout(20ms);
4818 mWindow =
4819 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4820 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004821 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004822 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004823
4824 // Set focused application.
4825 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4826
4827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004828 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004829 mWindow->consumeFocusEvent(true);
4830 }
4831
4832 virtual void TearDown() override {
4833 InputDispatcherTest::TearDown();
4834 mWindow.clear();
4835 }
4836
4837protected:
Chris Yea209fde2020-07-22 13:54:51 -07004838 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004839 sp<FakeWindowHandle> mWindow;
4840 static constexpr PointF WINDOW_LOCATION = {20, 20};
4841
4842 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4845 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004847 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4848 WINDOW_LOCATION));
4849 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004850
4851 sp<FakeWindowHandle> addSpyWindow() {
4852 sp<FakeWindowHandle> spy =
4853 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4854 spy->setTrustedOverlay(true);
4855 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004856 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004857 spy->setDispatchingTimeout(30ms);
4858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4859 return spy;
4860 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004861};
4862
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863// Send a tap and respond, which should not cause an ANR.
4864TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4865 tapOnWindow();
4866 mWindow->consumeMotionDown();
4867 mWindow->consumeMotionUp();
4868 ASSERT_TRUE(mDispatcher->waitForIdle());
4869 mFakePolicy->assertNotifyAnrWasNotCalled();
4870}
4871
4872// Send a regular key and respond, which should not cause an ANR.
4873TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4876 ASSERT_TRUE(mDispatcher->waitForIdle());
4877 mFakePolicy->assertNotifyAnrWasNotCalled();
4878}
4879
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004880TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4881 mWindow->setFocusable(false);
4882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4883 mWindow->consumeFocusEvent(false);
4884
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004885 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004886 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004887 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4888 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004890 // Key will not go to window because we have no focused window.
4891 // The 'no focused window' ANR timer should start instead.
4892
4893 // Now, the focused application goes away.
4894 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4895 // The key should get dropped and there should be no ANR.
4896
4897 ASSERT_TRUE(mDispatcher->waitForIdle());
4898 mFakePolicy->assertNotifyAnrWasNotCalled();
4899}
4900
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004901// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4903// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004904TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4907 WINDOW_LOCATION));
4908
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004909 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4910 ASSERT_TRUE(sequenceNum);
4911 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004912 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914 mWindow->finishEvent(*sequenceNum);
4915 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4916 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004917 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004918 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004919}
4920
4921// Send a key to the app and have the app not respond right away.
4922TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4923 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004925 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4926 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004927 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004928 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004929 ASSERT_TRUE(mDispatcher->waitForIdle());
4930}
4931
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004932// We have a focused application, but no focused window
4933TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004934 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4936 mWindow->consumeFocusEvent(false);
4937
4938 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004940 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4941 WINDOW_LOCATION));
4942 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4943 mDispatcher->waitForIdle();
4944 mFakePolicy->assertNotifyAnrWasNotCalled();
4945
4946 // Once a focused event arrives, we get an ANR for this application
4947 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4948 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004949 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004950 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004951 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004952 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004953 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004954 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004955 ASSERT_TRUE(mDispatcher->waitForIdle());
4956}
4957
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004958/**
4959 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4960 * there will not be an ANR.
4961 */
4962TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4963 mWindow->setFocusable(false);
4964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4965 mWindow->consumeFocusEvent(false);
4966
4967 KeyEvent event;
4968 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4969 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4970
4971 // Define a valid key down event that is stale (too old).
4972 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4973 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4974 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4975
4976 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4977
4978 InputEventInjectionResult result =
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004979 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004980 InputEventInjectionSync::WAIT_FOR_RESULT,
4981 INJECT_EVENT_TIMEOUT, policyFlags);
4982 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4983 << "Injection should fail because the event is stale";
4984
4985 ASSERT_TRUE(mDispatcher->waitForIdle());
4986 mFakePolicy->assertNotifyAnrWasNotCalled();
4987 mWindow->assertNoEvents();
4988}
4989
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004990// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004991// Make sure that we don't notify policy twice about the same ANR.
4992TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004993 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4995 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996
4997 // Once a focused event arrives, we get an ANR for this application
4998 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4999 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005000 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005001 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005002 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005003 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004 const std::chrono::duration appTimeout =
5005 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005006 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005007
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005008 std::this_thread::sleep_for(appTimeout);
5009 // ANR should not be raised again. It is up to policy to do that if it desires.
5010 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005011
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005012 // If we now get a focused window, the ANR should stop, but the policy handles that via
5013 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014 ASSERT_TRUE(mDispatcher->waitForIdle());
5015}
5016
5017// We have a focused application, but no focused window
5018TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07005019 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5021 mWindow->consumeFocusEvent(false);
5022
5023 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005024 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005026 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5027 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028
5029 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005030 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031
5032 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005033 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005034 ASSERT_TRUE(mDispatcher->waitForIdle());
5035 mWindow->assertNoEvents();
5036}
5037
5038/**
5039 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
5040 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
5041 * If we process 1 of the events, but ANR on the second event with the same timestamp,
5042 * the ANR mechanism should still work.
5043 *
5044 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
5045 * DOWN event, while not responding on the second one.
5046 */
5047TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
5048 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
5049 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5050 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5051 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5052 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005053 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054
5055 // Now send ACTION_UP, with identical timestamp
5056 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
5057 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
5058 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
5059 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005060 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005061
5062 // We have now sent down and up. Let's consume first event and then ANR on the second.
5063 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5064 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005065 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005066}
5067
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005068// A spy window can receive an ANR
5069TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
5070 sp<FakeWindowHandle> spy = addSpyWindow();
5071
5072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5073 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5074 WINDOW_LOCATION));
5075 mWindow->consumeMotionDown();
5076
5077 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5078 ASSERT_TRUE(sequenceNum);
5079 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005080 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005081
5082 spy->finishEvent(*sequenceNum);
5083 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
5084 0 /*flags*/);
5085 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005086 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005087}
5088
5089// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005091TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5092 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005093
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5095 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005098
5099 // Stuck on the ACTION_UP
5100 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005101 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005103 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005104 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005105 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5106 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005107
5108 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5109 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005110 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005111 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005112 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113}
5114
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005115// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005117TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5118 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005119
5120 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005121 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5122 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005123
5124 mWindow->consumeMotionDown();
5125 // Stuck on the ACTION_UP
5126 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005127 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005128
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005129 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005130 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005131 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5132 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005133
5134 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5135 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005136 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005137 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005138 spy->assertNoEvents();
5139}
5140
5141TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5142 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5143
5144 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5145
5146 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5147 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5148 WINDOW_LOCATION));
5149
5150 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5151 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5152 ASSERT_TRUE(consumeSeq);
5153
Prabir Pradhanedd96402022-02-15 01:46:16 -08005154 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005155
5156 monitor.finishEvent(*consumeSeq);
5157 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5158
5159 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005160 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005161}
5162
5163// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5164// process events, you don't get an anr. When the window later becomes unresponsive again, you
5165// get an ANR again.
5166// 1. tap -> block on ACTION_UP -> receive ANR
5167// 2. consume all pending events (= queue becomes healthy again)
5168// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5169TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5170 tapOnWindow();
5171
5172 mWindow->consumeMotionDown();
5173 // Block on ACTION_UP
5174 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005175 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005176 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5177 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005178 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005179 mWindow->assertNoEvents();
5180
5181 tapOnWindow();
5182 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005183 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005184 mWindow->consumeMotionUp();
5185
5186 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005187 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005188 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005189 mWindow->assertNoEvents();
5190}
5191
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005192// If a connection remains unresponsive for a while, make sure policy is only notified once about
5193// it.
5194TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5197 WINDOW_LOCATION));
5198
5199 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005200 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005201 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005202 // 'notifyConnectionUnresponsive' should only be called once per connection
5203 mFakePolicy->assertNotifyAnrWasNotCalled();
5204 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005205 mWindow->consumeMotionDown();
5206 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5207 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5208 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005209 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005210 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005211 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212}
5213
5214/**
5215 * If a window is processing a motion event, and then a key event comes in, the key event should
5216 * not to to the focused window until the motion is processed.
5217 *
5218 * Warning!!!
5219 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5220 * and the injection timeout that we specify when injecting the key.
5221 * We must have the injection timeout (10ms) be smaller than
5222 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5223 *
5224 * If that value changes, this test should also change.
5225 */
5226TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5227 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5229
5230 tapOnWindow();
5231 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5232 ASSERT_TRUE(downSequenceNum);
5233 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5234 ASSERT_TRUE(upSequenceNum);
5235 // Don't finish the events yet, and send a key
5236 // Injection will "succeed" because we will eventually give up and send the key to the focused
5237 // window even if motions are still being processed. But because the injection timeout is short,
5238 // we will receive INJECTION_TIMED_OUT as the result.
5239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005240 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005242 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5243 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244 // Key will not be sent to the window, yet, because the window is still processing events
5245 // and the key remains pending, waiting for the touch events to be processed
5246 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5247 ASSERT_FALSE(keySequenceNum);
5248
5249 std::this_thread::sleep_for(500ms);
5250 // if we wait long enough though, dispatcher will give up, and still send the key
5251 // to the focused window, even though we have not yet finished the motion event
5252 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5253 mWindow->finishEvent(*downSequenceNum);
5254 mWindow->finishEvent(*upSequenceNum);
5255}
5256
5257/**
5258 * If a window is processing a motion event, and then a key event comes in, the key event should
5259 * not go to the focused window until the motion is processed.
5260 * If then a new motion comes in, then the pending key event should be going to the currently
5261 * focused window right away.
5262 */
5263TEST_F(InputDispatcherSingleWindowAnr,
5264 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5265 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5267
5268 tapOnWindow();
5269 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5270 ASSERT_TRUE(downSequenceNum);
5271 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5272 ASSERT_TRUE(upSequenceNum);
5273 // Don't finish the events yet, and send a key
5274 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005275 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005276 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005278 // At this point, key is still pending, and should not be sent to the application yet.
5279 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5280 ASSERT_FALSE(keySequenceNum);
5281
5282 // Now tap down again. It should cause the pending key to go to the focused window right away.
5283 tapOnWindow();
5284 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5285 // the other events yet. We can finish events in any order.
5286 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5287 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5288 mWindow->consumeMotionDown();
5289 mWindow->consumeMotionUp();
5290 mWindow->assertNoEvents();
5291}
5292
5293class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5294 virtual void SetUp() override {
5295 InputDispatcherTest::SetUp();
5296
Chris Yea209fde2020-07-22 13:54:51 -07005297 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005298 mApplication->setDispatchingTimeout(10ms);
5299 mUnfocusedWindow =
5300 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5301 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005302 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005303 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005304
5305 mFocusedWindow =
5306 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005307 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005308 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005309
5310 // Set focused application.
5311 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005312 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005313
5314 // Expect one focus window exist in display.
5315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005316 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317 mFocusedWindow->consumeFocusEvent(true);
5318 }
5319
5320 virtual void TearDown() override {
5321 InputDispatcherTest::TearDown();
5322
5323 mUnfocusedWindow.clear();
5324 mFocusedWindow.clear();
5325 }
5326
5327protected:
Chris Yea209fde2020-07-22 13:54:51 -07005328 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005329 sp<FakeWindowHandle> mUnfocusedWindow;
5330 sp<FakeWindowHandle> mFocusedWindow;
5331 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5332 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5333 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5334
5335 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5336
5337 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5338
5339private:
5340 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5343 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5346 location));
5347 }
5348};
5349
5350// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5351// should be ANR'd first.
5352TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005354 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5355 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005356 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005357 mFocusedWindow->consumeMotionDown();
5358 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5359 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5360 // We consumed all events, so no ANR
5361 ASSERT_TRUE(mDispatcher->waitForIdle());
5362 mFakePolicy->assertNotifyAnrWasNotCalled();
5363
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005364 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005365 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5366 FOCUSED_WINDOW_LOCATION));
5367 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5368 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005369
5370 const std::chrono::duration timeout =
5371 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005372 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005373 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5374 // sequence to make it consistent
5375 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005377 mFocusedWindow->consumeMotionDown();
5378 // This cancel is generated because the connection was unresponsive
5379 mFocusedWindow->consumeMotionCancel();
5380 mFocusedWindow->assertNoEvents();
5381 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005382 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005383 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5384 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005385 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005386}
5387
5388// If we have 2 windows with identical timeouts that are both unresponsive,
5389// it doesn't matter which order they should have ANR.
5390// But we should receive ANR for both.
5391TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5392 // Set the timeout for unfocused window to match the focused window
5393 mUnfocusedWindow->setDispatchingTimeout(10ms);
5394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5395
5396 tapOnFocusedWindow();
5397 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005398 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5399 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5400 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005401
5402 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005403 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5404 mFocusedWindow->getToken() == anrConnectionToken2);
5405 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5406 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005407
5408 ASSERT_TRUE(mDispatcher->waitForIdle());
5409 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005410
5411 mFocusedWindow->consumeMotionDown();
5412 mFocusedWindow->consumeMotionUp();
5413 mUnfocusedWindow->consumeMotionOutside();
5414
Prabir Pradhanedd96402022-02-15 01:46:16 -08005415 sp<IBinder> responsiveToken1, responsiveToken2;
5416 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5417 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005418
5419 // Both applications should be marked as responsive, in any order
5420 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5421 mFocusedWindow->getToken() == responsiveToken2);
5422 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5423 mUnfocusedWindow->getToken() == responsiveToken2);
5424 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005425}
5426
5427// If a window is already not responding, the second tap on the same window should be ignored.
5428// We should also log an error to account for the dropped event (not tested here).
5429// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5430TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5431 tapOnFocusedWindow();
5432 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5433 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5434 // Receive the events, but don't respond
5435 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5436 ASSERT_TRUE(downEventSequenceNum);
5437 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5438 ASSERT_TRUE(upEventSequenceNum);
5439 const std::chrono::duration timeout =
5440 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005441 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005442
5443 // Tap once again
5444 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005445 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005446 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5447 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005448 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005449 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5450 FOCUSED_WINDOW_LOCATION));
5451 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5452 // valid touch target
5453 mUnfocusedWindow->assertNoEvents();
5454
5455 // Consume the first tap
5456 mFocusedWindow->finishEvent(*downEventSequenceNum);
5457 mFocusedWindow->finishEvent(*upEventSequenceNum);
5458 ASSERT_TRUE(mDispatcher->waitForIdle());
5459 // The second tap did not go to the focused window
5460 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005461 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005462 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5463 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005464 mFakePolicy->assertNotifyAnrWasNotCalled();
5465}
5466
5467// If you tap outside of all windows, there will not be ANR
5468TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005469 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005470 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5471 LOCATION_OUTSIDE_ALL_WINDOWS));
5472 ASSERT_TRUE(mDispatcher->waitForIdle());
5473 mFakePolicy->assertNotifyAnrWasNotCalled();
5474}
5475
5476// Since the focused window is paused, tapping on it should not produce any events
5477TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5478 mFocusedWindow->setPaused(true);
5479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5480
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005481 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005482 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5483 FOCUSED_WINDOW_LOCATION));
5484
5485 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5486 ASSERT_TRUE(mDispatcher->waitForIdle());
5487 // Should not ANR because the window is paused, and touches shouldn't go to it
5488 mFakePolicy->assertNotifyAnrWasNotCalled();
5489
5490 mFocusedWindow->assertNoEvents();
5491 mUnfocusedWindow->assertNoEvents();
5492}
5493
5494/**
5495 * If a window is processing a motion event, and then a key event comes in, the key event should
5496 * not to to the focused window until the motion is processed.
5497 * If a different window becomes focused at this time, the key should go to that window instead.
5498 *
5499 * Warning!!!
5500 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5501 * and the injection timeout that we specify when injecting the key.
5502 * We must have the injection timeout (10ms) be smaller than
5503 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5504 *
5505 * If that value changes, this test should also change.
5506 */
5507TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5508 // Set a long ANR timeout to prevent it from triggering
5509 mFocusedWindow->setDispatchingTimeout(2s);
5510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5511
5512 tapOnUnfocusedWindow();
5513 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5514 ASSERT_TRUE(downSequenceNum);
5515 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5516 ASSERT_TRUE(upSequenceNum);
5517 // Don't finish the events yet, and send a key
5518 // Injection will succeed because we will eventually give up and send the key to the focused
5519 // window even if motions are still being processed.
5520
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005521 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005522 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005523 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005525 // Key will not be sent to the window, yet, because the window is still processing events
5526 // and the key remains pending, waiting for the touch events to be processed
5527 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5528 ASSERT_FALSE(keySequenceNum);
5529
5530 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005531 mFocusedWindow->setFocusable(false);
5532 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005534 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005535
5536 // Focus events should precede the key events
5537 mUnfocusedWindow->consumeFocusEvent(true);
5538 mFocusedWindow->consumeFocusEvent(false);
5539
5540 // Finish the tap events, which should unblock dispatcher
5541 mUnfocusedWindow->finishEvent(*downSequenceNum);
5542 mUnfocusedWindow->finishEvent(*upSequenceNum);
5543
5544 // Now that all queues are cleared and no backlog in the connections, the key event
5545 // can finally go to the newly focused "mUnfocusedWindow".
5546 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5547 mFocusedWindow->assertNoEvents();
5548 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005549 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005550}
5551
5552// When the touch stream is split across 2 windows, and one of them does not respond,
5553// then ANR should be raised and the touch should be canceled for the unresponsive window.
5554// The other window should not be affected by that.
5555TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5556 // Touch Window 1
5557 NotifyMotionArgs motionArgs =
5558 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5559 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5560 mDispatcher->notifyMotion(&motionArgs);
5561 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5562 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5563
5564 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005565 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5566 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567 mDispatcher->notifyMotion(&motionArgs);
5568
5569 const std::chrono::duration timeout =
5570 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005571 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005572
5573 mUnfocusedWindow->consumeMotionDown();
5574 mFocusedWindow->consumeMotionDown();
5575 // Focused window may or may not receive ACTION_MOVE
5576 // But it should definitely receive ACTION_CANCEL due to the ANR
5577 InputEvent* event;
5578 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5579 ASSERT_TRUE(moveOrCancelSequenceNum);
5580 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5581 ASSERT_NE(nullptr, event);
5582 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5583 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5584 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5585 mFocusedWindow->consumeMotionCancel();
5586 } else {
5587 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5588 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005589 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005590 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5591 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005592
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005593 mUnfocusedWindow->assertNoEvents();
5594 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005595 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005596}
5597
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005598/**
5599 * If we have no focused window, and a key comes in, we start the ANR timer.
5600 * The focused application should add a focused window before the timer runs out to prevent ANR.
5601 *
5602 * If the user touches another application during this time, the key should be dropped.
5603 * Next, if a new focused window comes in, without toggling the focused application,
5604 * then no ANR should occur.
5605 *
5606 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5607 * but in some cases the policy may not update the focused application.
5608 */
5609TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5610 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5611 std::make_shared<FakeApplicationHandle>();
5612 focusedApplication->setDispatchingTimeout(60ms);
5613 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5614 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5615 mFocusedWindow->setFocusable(false);
5616
5617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5618 mFocusedWindow->consumeFocusEvent(false);
5619
5620 // Send a key. The ANR timer should start because there is no focused window.
5621 // 'focusedApplication' will get blamed if this timer completes.
5622 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005623 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005624 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005625 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5626 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005628
5629 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5630 // then the injected touches won't cause the focused event to get dropped.
5631 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5632 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5633 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5634 // For this test, it means that the key would get delivered to the window once it becomes
5635 // focused.
5636 std::this_thread::sleep_for(10ms);
5637
5638 // Touch unfocused window. This should force the pending key to get dropped.
5639 NotifyMotionArgs motionArgs =
5640 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5641 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5642 mDispatcher->notifyMotion(&motionArgs);
5643
5644 // We do not consume the motion right away, because that would require dispatcher to first
5645 // process (== drop) the key event, and by that time, ANR will be raised.
5646 // Set the focused window first.
5647 mFocusedWindow->setFocusable(true);
5648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5649 setFocusedWindow(mFocusedWindow);
5650 mFocusedWindow->consumeFocusEvent(true);
5651 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5652 // to another application. This could be a bug / behaviour in the policy.
5653
5654 mUnfocusedWindow->consumeMotionDown();
5655
5656 ASSERT_TRUE(mDispatcher->waitForIdle());
5657 // Should not ANR because we actually have a focused window. It was just added too slowly.
5658 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5659}
5660
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005661// These tests ensure we cannot send touch events to a window that's positioned behind a window
5662// that has feature NO_INPUT_CHANNEL.
5663// Layout:
5664// Top (closest to user)
5665// mNoInputWindow (above all windows)
5666// mBottomWindow
5667// Bottom (furthest from user)
5668class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5669 virtual void SetUp() override {
5670 InputDispatcherTest::SetUp();
5671
5672 mApplication = std::make_shared<FakeApplicationHandle>();
5673 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5674 "Window without input channel", ADISPLAY_ID_DEFAULT,
5675 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5676
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005677 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005678 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5679 // It's perfectly valid for this window to not have an associated input channel
5680
5681 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5682 ADISPLAY_ID_DEFAULT);
5683 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5684
5685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5686 }
5687
5688protected:
5689 std::shared_ptr<FakeApplicationHandle> mApplication;
5690 sp<FakeWindowHandle> mNoInputWindow;
5691 sp<FakeWindowHandle> mBottomWindow;
5692};
5693
5694TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5695 PointF touchedPoint = {10, 10};
5696
5697 NotifyMotionArgs motionArgs =
5698 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5699 ADISPLAY_ID_DEFAULT, {touchedPoint});
5700 mDispatcher->notifyMotion(&motionArgs);
5701
5702 mNoInputWindow->assertNoEvents();
5703 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5704 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5705 // and therefore should prevent mBottomWindow from receiving touches
5706 mBottomWindow->assertNoEvents();
5707}
5708
5709/**
5710 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5711 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5712 */
5713TEST_F(InputDispatcherMultiWindowOcclusionTests,
5714 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5715 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5716 "Window with input channel and NO_INPUT_CHANNEL",
5717 ADISPLAY_ID_DEFAULT);
5718
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005719 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005720 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5722
5723 PointF touchedPoint = {10, 10};
5724
5725 NotifyMotionArgs motionArgs =
5726 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5727 ADISPLAY_ID_DEFAULT, {touchedPoint});
5728 mDispatcher->notifyMotion(&motionArgs);
5729
5730 mNoInputWindow->assertNoEvents();
5731 mBottomWindow->assertNoEvents();
5732}
5733
Vishnu Nair958da932020-08-21 17:12:37 -07005734class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5735protected:
5736 std::shared_ptr<FakeApplicationHandle> mApp;
5737 sp<FakeWindowHandle> mWindow;
5738 sp<FakeWindowHandle> mMirror;
5739
5740 virtual void SetUp() override {
5741 InputDispatcherTest::SetUp();
5742 mApp = std::make_shared<FakeApplicationHandle>();
5743 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5744 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5745 mWindow->getToken());
5746 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5747 mWindow->setFocusable(true);
5748 mMirror->setFocusable(true);
5749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5750 }
5751};
5752
5753TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5754 // Request focus on a mirrored window
5755 setFocusedWindow(mMirror);
5756
5757 // window gets focused
5758 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5760 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005761 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5762}
5763
5764// A focused & mirrored window remains focused only if the window and its mirror are both
5765// focusable.
5766TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5767 setFocusedWindow(mMirror);
5768
5769 // window gets focused
5770 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5772 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005773 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5775 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005776 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5777
5778 mMirror->setFocusable(false);
5779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5780
5781 // window loses focus since one of the windows associated with the token in not focusable
5782 mWindow->consumeFocusEvent(false);
5783
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005784 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5785 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005786 mWindow->assertNoEvents();
5787}
5788
5789// A focused & mirrored window remains focused until the window and its mirror both become
5790// invisible.
5791TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5792 setFocusedWindow(mMirror);
5793
5794 // window gets focused
5795 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5797 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005798 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005799 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5800 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005801 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5802
5803 mMirror->setVisible(false);
5804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5805
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5807 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005808 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5810 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005811 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5812
5813 mWindow->setVisible(false);
5814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5815
5816 // window loses focus only after all windows associated with the token become invisible.
5817 mWindow->consumeFocusEvent(false);
5818
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005819 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5820 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005821 mWindow->assertNoEvents();
5822}
5823
5824// A focused & mirrored window remains focused until both windows are removed.
5825TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5826 setFocusedWindow(mMirror);
5827
5828 // window gets focused
5829 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5831 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005832 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5834 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005835 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5836
5837 // single window is removed but the window token remains focused
5838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5839
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005840 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5841 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005842 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5844 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005845 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5846
5847 // Both windows are removed
5848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5849 mWindow->consumeFocusEvent(false);
5850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005851 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5852 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005853 mWindow->assertNoEvents();
5854}
5855
5856// Focus request can be pending until one window becomes visible.
5857TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5858 // Request focus on an invisible mirror.
5859 mWindow->setVisible(false);
5860 mMirror->setVisible(false);
5861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5862 setFocusedWindow(mMirror);
5863
5864 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005866 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005867 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005868
5869 mMirror->setVisible(true);
5870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5871
5872 // window gets focused
5873 mWindow->consumeFocusEvent(true);
5874 // window gets the pending key event
5875 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5876}
Prabir Pradhan99987712020-11-10 18:43:05 -08005877
5878class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5879protected:
5880 std::shared_ptr<FakeApplicationHandle> mApp;
5881 sp<FakeWindowHandle> mWindow;
5882 sp<FakeWindowHandle> mSecondWindow;
5883
5884 void SetUp() override {
5885 InputDispatcherTest::SetUp();
5886 mApp = std::make_shared<FakeApplicationHandle>();
5887 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5888 mWindow->setFocusable(true);
5889 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5890 mSecondWindow->setFocusable(true);
5891
5892 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5894
5895 setFocusedWindow(mWindow);
5896 mWindow->consumeFocusEvent(true);
5897 }
5898
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005899 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5900 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005901 mDispatcher->notifyPointerCaptureChanged(&args);
5902 }
5903
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005904 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5905 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005906 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005907 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5908 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005909 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005910 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005911 }
5912};
5913
5914TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5915 // Ensure that capture cannot be obtained for unfocused windows.
5916 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5917 mFakePolicy->assertSetPointerCaptureNotCalled();
5918 mSecondWindow->assertNoEvents();
5919
5920 // Ensure that capture can be enabled from the focus window.
5921 requestAndVerifyPointerCapture(mWindow, true);
5922
5923 // Ensure that capture cannot be disabled from a window that does not have capture.
5924 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5925 mFakePolicy->assertSetPointerCaptureNotCalled();
5926
5927 // Ensure that capture can be disabled from the window with capture.
5928 requestAndVerifyPointerCapture(mWindow, false);
5929}
5930
5931TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005932 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005933
5934 setFocusedWindow(mSecondWindow);
5935
5936 // Ensure that the capture disabled event was sent first.
5937 mWindow->consumeCaptureEvent(false);
5938 mWindow->consumeFocusEvent(false);
5939 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005940 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005941
5942 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005943 notifyPointerCaptureChanged({});
5944 notifyPointerCaptureChanged(request);
5945 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005946 mWindow->assertNoEvents();
5947 mSecondWindow->assertNoEvents();
5948 mFakePolicy->assertSetPointerCaptureNotCalled();
5949}
5950
5951TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005952 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005953
5954 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005955 notifyPointerCaptureChanged({});
5956 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005957
5958 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005959 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005960 mWindow->consumeCaptureEvent(false);
5961 mWindow->assertNoEvents();
5962}
5963
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005964TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5965 requestAndVerifyPointerCapture(mWindow, true);
5966
5967 // The first window loses focus.
5968 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005969 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005970 mWindow->consumeCaptureEvent(false);
5971
5972 // Request Pointer Capture from the second window before the notification from InputReader
5973 // arrives.
5974 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005975 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005976
5977 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005978 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005979
5980 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005981 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005982
5983 mSecondWindow->consumeFocusEvent(true);
5984 mSecondWindow->consumeCaptureEvent(true);
5985}
5986
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005987TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5988 // App repeatedly enables and disables capture.
5989 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5990 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5991 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5992 mFakePolicy->assertSetPointerCaptureCalled(false);
5993 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5994 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5995
5996 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5997 // first request is now stale, this should do nothing.
5998 notifyPointerCaptureChanged(firstRequest);
5999 mWindow->assertNoEvents();
6000
6001 // InputReader notifies that the second request was enabled.
6002 notifyPointerCaptureChanged(secondRequest);
6003 mWindow->consumeCaptureEvent(true);
6004}
6005
Prabir Pradhan7092e262022-05-03 16:51:09 +00006006TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
6007 requestAndVerifyPointerCapture(mWindow, true);
6008
6009 // App toggles pointer capture off and on.
6010 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
6011 mFakePolicy->assertSetPointerCaptureCalled(false);
6012
6013 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
6014 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
6015
6016 // InputReader notifies that the latest "enable" request was processed, while skipping over the
6017 // preceding "disable" request.
6018 notifyPointerCaptureChanged(enableRequest);
6019
6020 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
6021 // any notifications.
6022 mWindow->assertNoEvents();
6023}
6024
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006025class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
6026protected:
6027 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00006028
6029 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
6030 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
6031
6032 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
6033 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6034
6035 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
6036 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
6037 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
6038 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
6039 MAXIMUM_OBSCURING_OPACITY);
6040
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006041 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006042 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006043 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006044
6045 sp<FakeWindowHandle> mTouchWindow;
6046
6047 virtual void SetUp() override {
6048 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006049 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006050 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
6051 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
6052 }
6053
6054 virtual void TearDown() override {
6055 InputDispatcherTest::TearDown();
6056 mTouchWindow.clear();
6057 }
6058
chaviw3277faf2021-05-19 16:45:23 -05006059 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
6060 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006061 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006062 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006063 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006064 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006065 return window;
6066 }
6067
6068 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
6069 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
6070 sp<FakeWindowHandle> window =
6071 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
6072 // Generate an arbitrary PID based on the UID
6073 window->setOwnerInfo(1777 + (uid % 10000), uid);
6074 return window;
6075 }
6076
6077 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6078 NotifyMotionArgs args =
6079 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6080 ADISPLAY_ID_DEFAULT, points);
6081 mDispatcher->notifyMotion(&args);
6082 }
6083};
6084
6085TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006086 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006087 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006088 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006089
6090 touch();
6091
6092 mTouchWindow->assertNoEvents();
6093}
6094
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006095TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006096 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6097 const sp<FakeWindowHandle>& w =
6098 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6099 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6100
6101 touch();
6102
6103 mTouchWindow->assertNoEvents();
6104}
6105
6106TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006107 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6108 const sp<FakeWindowHandle>& w =
6109 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6111
6112 touch();
6113
6114 w->assertNoEvents();
6115}
6116
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006117TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006118 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006120
6121 touch();
6122
6123 mTouchWindow->consumeAnyMotionDown();
6124}
6125
6126TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006127 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006128 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006129 w->setFrame(Rect(0, 0, 50, 50));
6130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006131
6132 touch({PointF{100, 100}});
6133
6134 mTouchWindow->consumeAnyMotionDown();
6135}
6136
6137TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006138 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006139 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6141
6142 touch();
6143
6144 mTouchWindow->consumeAnyMotionDown();
6145}
6146
6147TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6148 const sp<FakeWindowHandle>& w =
6149 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006151
6152 touch();
6153
6154 mTouchWindow->consumeAnyMotionDown();
6155}
6156
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006157TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6158 const sp<FakeWindowHandle>& w =
6159 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6160 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6161
6162 touch();
6163
6164 w->assertNoEvents();
6165}
6166
6167/**
6168 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6169 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6170 * window, the occluding window will still receive ACTION_OUTSIDE event.
6171 */
6172TEST_F(InputDispatcherUntrustedTouchesTest,
6173 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6174 const sp<FakeWindowHandle>& w =
6175 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006176 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6178
6179 touch();
6180
6181 w->consumeMotionOutside();
6182}
6183
6184TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6185 const sp<FakeWindowHandle>& w =
6186 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006187 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6189
6190 touch();
6191
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006192 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006193}
6194
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006195TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006196 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006197 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6198 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6200
6201 touch();
6202
6203 mTouchWindow->consumeAnyMotionDown();
6204}
6205
6206TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6207 const sp<FakeWindowHandle>& w =
6208 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6209 MAXIMUM_OBSCURING_OPACITY);
6210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006211
6212 touch();
6213
6214 mTouchWindow->consumeAnyMotionDown();
6215}
6216
6217TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006218 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006219 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6220 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006221 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6222
6223 touch();
6224
6225 mTouchWindow->assertNoEvents();
6226}
6227
6228TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6229 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6230 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006231 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6232 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006233 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006234 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6235 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006236 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6237
6238 touch();
6239
6240 mTouchWindow->assertNoEvents();
6241}
6242
6243TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6244 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6245 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006246 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6247 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006248 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006249 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6250 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6252
6253 touch();
6254
6255 mTouchWindow->consumeAnyMotionDown();
6256}
6257
6258TEST_F(InputDispatcherUntrustedTouchesTest,
6259 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6260 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006261 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6262 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006263 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006264 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6265 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6267
6268 touch();
6269
6270 mTouchWindow->consumeAnyMotionDown();
6271}
6272
6273TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6274 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006275 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6276 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006277 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006278 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6279 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006280 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006281
6282 touch();
6283
6284 mTouchWindow->assertNoEvents();
6285}
6286
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006287TEST_F(InputDispatcherUntrustedTouchesTest,
6288 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6289 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006290 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6291 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006292 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006293 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6294 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006295 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6296
6297 touch();
6298
6299 mTouchWindow->assertNoEvents();
6300}
6301
6302TEST_F(InputDispatcherUntrustedTouchesTest,
6303 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6304 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006305 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6306 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006307 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006308 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6309 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6311
6312 touch();
6313
6314 mTouchWindow->consumeAnyMotionDown();
6315}
6316
6317TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6318 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006319 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6320 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6322
6323 touch();
6324
6325 mTouchWindow->consumeAnyMotionDown();
6326}
6327
6328TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6329 const sp<FakeWindowHandle>& w =
6330 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6332
6333 touch();
6334
6335 mTouchWindow->consumeAnyMotionDown();
6336}
6337
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006338TEST_F(InputDispatcherUntrustedTouchesTest,
6339 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6340 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6341 const sp<FakeWindowHandle>& w =
6342 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6344
6345 touch();
6346
6347 mTouchWindow->assertNoEvents();
6348}
6349
6350TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6351 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6352 const sp<FakeWindowHandle>& w =
6353 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6355
6356 touch();
6357
6358 mTouchWindow->consumeAnyMotionDown();
6359}
6360
6361TEST_F(InputDispatcherUntrustedTouchesTest,
6362 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6363 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6364 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006365 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6366 OPACITY_ABOVE_THRESHOLD);
6367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6368
6369 touch();
6370
6371 mTouchWindow->consumeAnyMotionDown();
6372}
6373
6374TEST_F(InputDispatcherUntrustedTouchesTest,
6375 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6376 const sp<FakeWindowHandle>& w1 =
6377 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6378 OPACITY_BELOW_THRESHOLD);
6379 const sp<FakeWindowHandle>& w2 =
6380 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6381 OPACITY_BELOW_THRESHOLD);
6382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6383
6384 touch();
6385
6386 mTouchWindow->assertNoEvents();
6387}
6388
6389/**
6390 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6391 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6392 * (which alone would result in allowing touches) does not affect the blocking behavior.
6393 */
6394TEST_F(InputDispatcherUntrustedTouchesTest,
6395 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6396 const sp<FakeWindowHandle>& wB =
6397 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6398 OPACITY_BELOW_THRESHOLD);
6399 const sp<FakeWindowHandle>& wC =
6400 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6401 OPACITY_BELOW_THRESHOLD);
6402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6403
6404 touch();
6405
6406 mTouchWindow->assertNoEvents();
6407}
6408
6409/**
6410 * This test is testing that a window from a different UID but with same application token doesn't
6411 * block the touch. Apps can share the application token for close UI collaboration for example.
6412 */
6413TEST_F(InputDispatcherUntrustedTouchesTest,
6414 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6415 const sp<FakeWindowHandle>& w =
6416 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6417 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6419
6420 touch();
6421
6422 mTouchWindow->consumeAnyMotionDown();
6423}
6424
arthurhungb89ccb02020-12-30 16:19:01 +08006425class InputDispatcherDragTests : public InputDispatcherTest {
6426protected:
6427 std::shared_ptr<FakeApplicationHandle> mApp;
6428 sp<FakeWindowHandle> mWindow;
6429 sp<FakeWindowHandle> mSecondWindow;
6430 sp<FakeWindowHandle> mDragWindow;
Arthur Hung02701602022-07-15 09:35:36 +00006431 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6432 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006433
6434 void SetUp() override {
6435 InputDispatcherTest::SetUp();
6436 mApp = std::make_shared<FakeApplicationHandle>();
6437 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6438 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006439
6440 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6441 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006442
6443 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6445 }
6446
Arthur Hung02701602022-07-15 09:35:36 +00006447 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6448 switch (fromSource) {
6449 case AINPUT_SOURCE_TOUCHSCREEN:
6450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6452 ADISPLAY_ID_DEFAULT, {50, 50}))
6453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6454 break;
6455 case AINPUT_SOURCE_STYLUS:
6456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6457 injectMotionEvent(
6458 mDispatcher,
6459 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6460 AINPUT_SOURCE_STYLUS)
6461 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6462 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6463 .x(50)
6464 .y(50))
6465 .build()));
6466 break;
6467 case AINPUT_SOURCE_MOUSE:
6468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6469 injectMotionEvent(
6470 mDispatcher,
6471 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6472 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6473 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6474 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6475 .x(50)
6476 .y(50))
6477 .build()));
6478 break;
6479 default:
6480 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6481 }
arthurhungb89ccb02020-12-30 16:19:01 +08006482
6483 // Window should receive motion event.
6484 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006485 }
6486
6487 // Start performing drag, we will create a drag window and transfer touch to it.
6488 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6489 // Returns true on success.
Arthur Hung02701602022-07-15 09:35:36 +00006490 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006491 if (sendDown) {
Arthur Hung02701602022-07-15 09:35:36 +00006492 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006493 }
arthurhungb89ccb02020-12-30 16:19:01 +08006494
6495 // The drag window covers the entire display
6496 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6497 mDispatcher->setInputWindows(
6498 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6499
6500 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006501 bool transferred =
6502 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6503 true /* isDragDrop */);
6504 if (transferred) {
6505 mWindow->consumeMotionCancel();
6506 mDragWindow->consumeMotionDown();
6507 }
6508 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006509 }
6510};
6511
6512TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hung02701602022-07-15 09:35:36 +00006513 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006514
6515 // Move on window.
6516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6517 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6518 ADISPLAY_ID_DEFAULT, {50, 50}))
6519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6520 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6521 mWindow->consumeDragEvent(false, 50, 50);
6522 mSecondWindow->assertNoEvents();
6523
6524 // Move to another window.
6525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6526 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6527 ADISPLAY_ID_DEFAULT, {150, 50}))
6528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6529 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6530 mWindow->consumeDragEvent(true, 150, 50);
6531 mSecondWindow->consumeDragEvent(false, 50, 50);
6532
6533 // Move back to original 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->consumeDragEvent(true, -50, 50);
6541
6542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6543 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6545 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6546 mWindow->assertNoEvents();
6547 mSecondWindow->assertNoEvents();
6548}
6549
arthurhungf452d0b2021-01-06 00:19:52 +08006550TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006551 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006552
6553 // Move on window.
6554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6555 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6556 ADISPLAY_ID_DEFAULT, {50, 50}))
6557 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6558 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6559 mWindow->consumeDragEvent(false, 50, 50);
6560 mSecondWindow->assertNoEvents();
6561
6562 // Move to another window.
6563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6564 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6565 ADISPLAY_ID_DEFAULT, {150, 50}))
6566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6567 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6568 mWindow->consumeDragEvent(true, 150, 50);
6569 mSecondWindow->consumeDragEvent(false, 50, 50);
6570
6571 // drop to another window.
6572 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6573 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6574 {150, 50}))
6575 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6576 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6577 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6578 mWindow->assertNoEvents();
6579 mSecondWindow->assertNoEvents();
6580}
6581
arthurhung6d4bed92021-03-17 11:59:33 +08006582TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006583 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006584
6585 // Move on window and keep button pressed.
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionEvent(mDispatcher,
6588 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6589 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6590 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6591 .x(50)
6592 .y(50))
6593 .build()))
6594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6595 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6596 mWindow->consumeDragEvent(false, 50, 50);
6597 mSecondWindow->assertNoEvents();
6598
6599 // Move to another window and release button, expect to drop item.
6600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6601 injectMotionEvent(mDispatcher,
6602 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6603 .buttonState(0)
6604 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6605 .x(150)
6606 .y(50))
6607 .build()))
6608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6609 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6610 mWindow->assertNoEvents();
6611 mSecondWindow->assertNoEvents();
6612 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6613
6614 // nothing to the window.
6615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6616 injectMotionEvent(mDispatcher,
6617 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6618 .buttonState(0)
6619 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6620 .x(150)
6621 .y(50))
6622 .build()))
6623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6624 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6625 mWindow->assertNoEvents();
6626 mSecondWindow->assertNoEvents();
6627}
6628
Arthur Hung54745652022-04-20 07:17:41 +00006629TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung02701602022-07-15 09:35:36 +00006630 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006631
6632 // Set second window invisible.
6633 mSecondWindow->setVisible(false);
6634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6635
6636 // Move on window.
6637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6638 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6639 ADISPLAY_ID_DEFAULT, {50, 50}))
6640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6641 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6642 mWindow->consumeDragEvent(false, 50, 50);
6643 mSecondWindow->assertNoEvents();
6644
6645 // Move to another window.
6646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6647 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6648 ADISPLAY_ID_DEFAULT, {150, 50}))
6649 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6650 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6651 mWindow->consumeDragEvent(true, 150, 50);
6652 mSecondWindow->assertNoEvents();
6653
6654 // drop to another window.
6655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6656 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6657 {150, 50}))
6658 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6659 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6660 mFakePolicy->assertDropTargetEquals(nullptr);
6661 mWindow->assertNoEvents();
6662 mSecondWindow->assertNoEvents();
6663}
6664
Arthur Hung54745652022-04-20 07:17:41 +00006665TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hung02701602022-07-15 09:35:36 +00006666 // Ensure window could track pointerIds if it didn't support split touch.
6667 mWindow->setPreventSplitting(true);
6668
Arthur Hung54745652022-04-20 07:17:41 +00006669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6670 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6671 {50, 50}))
6672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6673 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6674
6675 const MotionEvent secondFingerDownEvent =
6676 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6677 .displayId(ADISPLAY_ID_DEFAULT)
6678 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6679 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6680 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6681 .build();
6682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6683 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6684 InputEventInjectionSync::WAIT_FOR_RESULT))
6685 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6686 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6687
6688 // Should not perform drag and drop when window has multi fingers.
Arthur Hung02701602022-07-15 09:35:36 +00006689 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006690}
6691
6692TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6693 // First down on second window.
6694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6695 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6696 {150, 50}))
6697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6698
6699 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6700
6701 // Second down on first window.
6702 const MotionEvent secondFingerDownEvent =
6703 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6704 .displayId(ADISPLAY_ID_DEFAULT)
6705 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6706 .pointer(
6707 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6708 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6709 .build();
6710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6711 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6712 InputEventInjectionSync::WAIT_FOR_RESULT))
6713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6714 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6715
6716 // Perform drag and drop from first window.
Arthur Hung02701602022-07-15 09:35:36 +00006717 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006718
6719 // Move on window.
6720 const MotionEvent secondFingerMoveEvent =
6721 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6722 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6723 .pointer(
6724 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6725 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6726 .build();
6727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6728 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6729 InputEventInjectionSync::WAIT_FOR_RESULT));
6730 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6731 mWindow->consumeDragEvent(false, 50, 50);
6732 mSecondWindow->consumeMotionMove();
6733
6734 // Release the drag pointer should perform drop.
6735 const MotionEvent secondFingerUpEvent =
6736 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6737 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6738 .pointer(
6739 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6740 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6741 .build();
6742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6743 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6744 InputEventInjectionSync::WAIT_FOR_RESULT));
6745 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6746 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6747 mWindow->assertNoEvents();
6748 mSecondWindow->consumeMotionMove();
6749}
6750
Arthur Hung3915c1f2022-05-31 07:17:17 +00006751TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hung02701602022-07-15 09:35:36 +00006752 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006753
6754 // Update window of second display.
6755 sp<FakeWindowHandle> windowInSecondary =
6756 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6757 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6758
6759 // Let second display has a touch state.
6760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6761 injectMotionEvent(mDispatcher,
6762 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6763 AINPUT_SOURCE_TOUCHSCREEN)
6764 .displayId(SECOND_DISPLAY_ID)
6765 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6766 .x(100)
6767 .y(100))
6768 .build()));
6769 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6770 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6771 // Update window again.
6772 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6773
6774 // Move on window.
6775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6776 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6777 ADISPLAY_ID_DEFAULT, {50, 50}))
6778 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6779 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6780 mWindow->consumeDragEvent(false, 50, 50);
6781 mSecondWindow->assertNoEvents();
6782
6783 // Move to another window.
6784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6785 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6786 ADISPLAY_ID_DEFAULT, {150, 50}))
6787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6788 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6789 mWindow->consumeDragEvent(true, 150, 50);
6790 mSecondWindow->consumeDragEvent(false, 50, 50);
6791
6792 // drop to another window.
6793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6794 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6795 {150, 50}))
6796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6797 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6798 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6799 mWindow->assertNoEvents();
6800 mSecondWindow->assertNoEvents();
6801}
6802
Arthur Hung02701602022-07-15 09:35:36 +00006803TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6804 startDrag(true, AINPUT_SOURCE_MOUSE);
6805 // Move on window.
6806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6807 injectMotionEvent(mDispatcher,
6808 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6809 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6810 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6811 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6812 .x(50)
6813 .y(50))
6814 .build()))
6815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6816 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6817 mWindow->consumeDragEvent(false, 50, 50);
6818 mSecondWindow->assertNoEvents();
6819
6820 // Move to another window.
6821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6822 injectMotionEvent(mDispatcher,
6823 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6824 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6825 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6826 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6827 .x(150)
6828 .y(50))
6829 .build()))
6830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6831 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6832 mWindow->consumeDragEvent(true, 150, 50);
6833 mSecondWindow->consumeDragEvent(false, 50, 50);
6834
6835 // drop to another window.
6836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6837 injectMotionEvent(mDispatcher,
6838 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6839 .buttonState(0)
6840 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6841 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6842 .x(150)
6843 .y(50))
6844 .build()))
6845 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6846 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6847 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6848 mWindow->assertNoEvents();
6849 mSecondWindow->assertNoEvents();
6850}
6851
Vishnu Nair062a8672021-09-03 16:07:44 -07006852class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6853
6854TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6856 sp<FakeWindowHandle> window =
6857 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006858 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006859 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6860 window->setFocusable(true);
6861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6862 setFocusedWindow(window);
6863 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6864
6865 // With the flag set, window should not get any input
6866 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6867 mDispatcher->notifyKey(&keyArgs);
6868 window->assertNoEvents();
6869
6870 NotifyMotionArgs motionArgs =
6871 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6872 ADISPLAY_ID_DEFAULT);
6873 mDispatcher->notifyMotion(&motionArgs);
6874 window->assertNoEvents();
6875
6876 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006877 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6879
6880 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6881 mDispatcher->notifyKey(&keyArgs);
6882 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6883
6884 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6885 ADISPLAY_ID_DEFAULT);
6886 mDispatcher->notifyMotion(&motionArgs);
6887 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6888 window->assertNoEvents();
6889}
6890
6891TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6892 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6893 std::make_shared<FakeApplicationHandle>();
6894 sp<FakeWindowHandle> obscuringWindow =
6895 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6896 ADISPLAY_ID_DEFAULT);
6897 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6898 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006899 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006900 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6901 sp<FakeWindowHandle> window =
6902 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006903 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006904 window->setOwnerInfo(222, 222);
6905 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6906 window->setFocusable(true);
6907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6908 setFocusedWindow(window);
6909 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6910
6911 // With the flag set, window should not get any input
6912 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6913 mDispatcher->notifyKey(&keyArgs);
6914 window->assertNoEvents();
6915
6916 NotifyMotionArgs motionArgs =
6917 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6918 ADISPLAY_ID_DEFAULT);
6919 mDispatcher->notifyMotion(&motionArgs);
6920 window->assertNoEvents();
6921
6922 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006923 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6925
6926 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6927 mDispatcher->notifyKey(&keyArgs);
6928 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6929
6930 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6931 ADISPLAY_ID_DEFAULT);
6932 mDispatcher->notifyMotion(&motionArgs);
6933 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6934 window->assertNoEvents();
6935}
6936
6937TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6938 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6939 std::make_shared<FakeApplicationHandle>();
6940 sp<FakeWindowHandle> obscuringWindow =
6941 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6942 ADISPLAY_ID_DEFAULT);
6943 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6944 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006945 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6947 sp<FakeWindowHandle> window =
6948 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006949 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006950 window->setOwnerInfo(222, 222);
6951 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6952 window->setFocusable(true);
6953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6954 setFocusedWindow(window);
6955 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6956
6957 // With the flag set, window should not get any input
6958 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6959 mDispatcher->notifyKey(&keyArgs);
6960 window->assertNoEvents();
6961
6962 NotifyMotionArgs motionArgs =
6963 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6964 ADISPLAY_ID_DEFAULT);
6965 mDispatcher->notifyMotion(&motionArgs);
6966 window->assertNoEvents();
6967
6968 // When the window is no longer obscured because it went on top, it should get input
6969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6970
6971 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6972 mDispatcher->notifyKey(&keyArgs);
6973 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6974
6975 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6976 ADISPLAY_ID_DEFAULT);
6977 mDispatcher->notifyMotion(&motionArgs);
6978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6979 window->assertNoEvents();
6980}
6981
Antonio Kantekf16f2832021-09-28 04:39:20 +00006982class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6983protected:
6984 std::shared_ptr<FakeApplicationHandle> mApp;
6985 sp<FakeWindowHandle> mWindow;
6986 sp<FakeWindowHandle> mSecondWindow;
6987
6988 void SetUp() override {
6989 InputDispatcherTest::SetUp();
6990
6991 mApp = std::make_shared<FakeApplicationHandle>();
6992 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6993 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006994 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006995 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6996 mSecondWindow->setFocusable(true);
6997
6998 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00007000 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00007001
7002 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007003 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
7004 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07007005 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7006 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
7007 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00007008 }
7009
Antonio Kantekea47acb2021-12-23 12:41:25 -08007010 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00007011 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007012 mWindow->consumeTouchModeEvent(inTouchMode);
7013 mSecondWindow->consumeTouchModeEvent(inTouchMode);
7014 }
7015};
7016
Antonio Kantek26defcf2022-02-08 01:12:27 +00007017TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007018 const WindowInfo& windowInfo = *mWindow->getInfo();
7019 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
7020 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00007021}
7022
Antonio Kantek26defcf2022-02-08 01:12:27 +00007023TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
7024 const WindowInfo& windowInfo = *mWindow->getInfo();
7025 int32_t ownerPid = windowInfo.ownerPid;
7026 int32_t ownerUid = windowInfo.ownerUid;
7027 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7028 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
7029 ownerUid, /* hasPermission */ false));
7030 mWindow->assertNoEvents();
7031 mSecondWindow->assertNoEvents();
7032}
7033
7034TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
7035 const WindowInfo& windowInfo = *mWindow->getInfo();
7036 int32_t ownerPid = windowInfo.ownerPid;
7037 int32_t ownerUid = windowInfo.ownerUid;
7038 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
7039 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
7040 /* hasPermission */ true);
7041}
7042
Antonio Kantekf16f2832021-09-28 04:39:20 +00007043TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08007044 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00007045 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
7046 windowInfo.ownerPid, windowInfo.ownerUid,
7047 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00007048 mWindow->assertNoEvents();
7049 mSecondWindow->assertNoEvents();
7050}
7051
Antonio Kantek48710e42022-03-24 14:19:30 -07007052TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
7053 // Interact with the window first.
7054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
7055 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7056 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
7057
7058 // Then remove focus.
7059 mWindow->setFocusable(false);
7060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
7061
7062 // Assert that caller can switch touch mode by owning one of the last interacted window.
7063 const WindowInfo& windowInfo = *mWindow->getInfo();
7064 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
7065 windowInfo.ownerPid, windowInfo.ownerUid,
7066 /* hasPermission= */ false));
7067}
7068
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007069class InputDispatcherSpyWindowTest : public InputDispatcherTest {
7070public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007071 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007072 std::shared_ptr<FakeApplicationHandle> application =
7073 std::make_shared<FakeApplicationHandle>();
7074 std::string name = "Fake Spy ";
7075 name += std::to_string(mSpyCount++);
7076 sp<FakeWindowHandle> spy =
7077 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007078 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007079 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007080 return spy;
7081 }
7082
7083 sp<FakeWindowHandle> createForeground() {
7084 std::shared_ptr<FakeApplicationHandle> application =
7085 std::make_shared<FakeApplicationHandle>();
7086 sp<FakeWindowHandle> window =
7087 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007088 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007089 return window;
7090 }
7091
7092private:
7093 int mSpyCount{0};
7094};
7095
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007096using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007097/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007098 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7099 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007100TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7101 ScopedSilentDeath _silentDeath;
7102
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007103 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007104 spy->setTrustedOverlay(false);
7105 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7106 ".* not a trusted overlay");
7107}
7108
7109/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007110 * Input injection into a display with a spy window but no foreground windows should succeed.
7111 */
7112TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007113 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007114 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7115
7116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7117 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7119 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7120}
7121
7122/**
7123 * Verify the order in which different input windows receive events. The touched foreground window
7124 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7125 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7126 * receive events before ones belows it.
7127 *
7128 * Here, we set up a scenario with four windows in the following Z order from the top:
7129 * spy1, spy2, window, spy3.
7130 * We then inject an event and verify that the foreground "window" receives it first, followed by
7131 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7132 * window.
7133 */
7134TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7135 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007136 auto spy1 = createSpy();
7137 auto spy2 = createSpy();
7138 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7140 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7141 const size_t numChannels = channels.size();
7142
Michael Wright8e9a8562022-02-09 13:44:29 +00007143 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007144 if (!epollFd.ok()) {
7145 FAIL() << "Failed to create epoll fd";
7146 }
7147
7148 for (size_t i = 0; i < numChannels; i++) {
7149 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7150 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7151 FAIL() << "Failed to add fd to epoll";
7152 }
7153 }
7154
7155 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7156 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7158
7159 std::vector<size_t> eventOrder;
7160 std::vector<struct epoll_event> events(numChannels);
7161 for (;;) {
7162 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7163 (100ms).count());
7164 if (nFds < 0) {
7165 FAIL() << "Failed to call epoll_wait";
7166 }
7167 if (nFds == 0) {
7168 break; // epoll_wait timed out
7169 }
7170 for (int i = 0; i < nFds; i++) {
7171 ASSERT_EQ(EPOLLIN, events[i].events);
7172 eventOrder.push_back(events[i].data.u64);
7173 channels[i]->consumeMotionDown();
7174 }
7175 }
7176
7177 // Verify the order in which the events were received.
7178 EXPECT_EQ(3u, eventOrder.size());
7179 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7180 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7181 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7182}
7183
7184/**
7185 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7186 */
7187TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7188 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007189 auto spy = createSpy();
7190 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7192
7193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7194 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7195 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7196 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7197 spy->assertNoEvents();
7198}
7199
7200/**
7201 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7202 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7203 * to the window.
7204 */
7205TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7206 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007207 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007208 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7210
7211 // Inject an event outside the spy window's touchable region.
7212 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7213 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7214 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7215 window->consumeMotionDown();
7216 spy->assertNoEvents();
7217 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7218 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7219 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7220 window->consumeMotionUp();
7221 spy->assertNoEvents();
7222
7223 // Inject an event inside the spy window's touchable region.
7224 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7225 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7226 {5, 10}))
7227 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7228 window->consumeMotionDown();
7229 spy->consumeMotionDown();
7230}
7231
7232/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007233 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007234 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007235 */
7236TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7237 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007238 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007239 auto spy = createSpy();
7240 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007241 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007242 spy->setFrame(Rect{0, 0, 20, 20});
7243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7244
7245 // Inject an event outside the spy window's frame and touchable region.
7246 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007247 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7248 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007249 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7250 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007251 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007252}
7253
7254/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007255 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
7256 * any other windows - including other spy windows - will also be cancelled.
7257 */
7258TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
7259 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007260 auto spy1 = createSpy();
7261 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7263
7264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7265 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7266 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7267 window->consumeMotionDown();
7268 spy1->consumeMotionDown();
7269 spy2->consumeMotionDown();
7270
7271 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007272 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007273 spy2->assertNoEvents();
7274 spy1->consumeMotionCancel();
7275 window->consumeMotionCancel();
7276
7277 // The rest of the gesture should only be sent to the second spy window.
7278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7279 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7280 ADISPLAY_ID_DEFAULT))
7281 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7282 spy2->consumeMotionMove();
7283 spy1->assertNoEvents();
7284 window->assertNoEvents();
7285}
7286
7287/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007288 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7289 * in the middle of the gesture.
7290 */
7291TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
7292 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007293 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7295
7296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7297 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7299 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7300 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7301
7302 window->releaseChannel();
7303
7304 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7305
7306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7307 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7308 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7309 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7310}
7311
7312/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007313 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7314 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007315 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007316TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007317 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007318 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007319
7320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7321
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007322 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7324 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7325 {100, 200}))
7326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007327 spy->consumeMotionDown();
7328 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007329
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007330 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007331 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007332 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007333
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007334 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007335 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007336 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007337 .displayId(ADISPLAY_ID_DEFAULT)
7338 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7339 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7340 .x(100)
7341 .y(200))
7342 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7343 .build();
7344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7345 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7346 InputEventInjectionSync::WAIT_FOR_RESULT))
7347 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7348
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007349 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7350
7351 // Third finger goes down outside all windows, so injection should fail.
7352 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00007353 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007354 .displayId(ADISPLAY_ID_DEFAULT)
7355 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7356 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7357 .x(100)
7358 .y(200))
7359 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7360 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7361 .build();
7362 ASSERT_EQ(InputEventInjectionResult::FAILED,
7363 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7364 InputEventInjectionSync::WAIT_FOR_RESULT))
7365 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7366
7367 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007368 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007369}
7370
7371/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007372 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7373 * pointers that are down within its bounds.
7374 */
7375TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7376 auto windowLeft = createForeground();
7377 windowLeft->setFrame({0, 0, 100, 200});
7378 auto windowRight = createForeground();
7379 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007380 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007381 spy->setFrame({0, 0, 200, 200});
7382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7383
7384 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7385 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7386 {50, 50}))
7387 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7388 windowLeft->consumeMotionDown();
7389 spy->consumeMotionDown();
7390
7391 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007392 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007393 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7394 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7395 .pointer(
7396 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7397 .build();
7398 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7399 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7400 InputEventInjectionSync::WAIT_FOR_RESULT))
7401 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7402 windowRight->consumeMotionDown();
7403 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7404}
7405
7406/**
7407 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7408 * the spy should receive the second pointer with ACTION_DOWN.
7409 */
7410TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7411 auto window = createForeground();
7412 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007413 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007414 spyRight->setFrame({100, 0, 200, 200});
7415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7416
7417 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7418 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7419 {50, 50}))
7420 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7421 window->consumeMotionDown();
7422 spyRight->assertNoEvents();
7423
7424 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007425 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007426 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7427 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7428 .pointer(
7429 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7430 .build();
7431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7432 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7433 InputEventInjectionSync::WAIT_FOR_RESULT))
7434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7435 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7436 spyRight->consumeMotionDown();
7437}
7438
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007439/**
7440 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7441 * windows should be allowed to control split touch.
7442 */
7443TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007444 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007445 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007446 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007447 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007448
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007449 auto window = createForeground();
7450 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007451
7452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7453
7454 // First finger down, no window touched.
7455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7456 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7457 {100, 200}))
7458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7459 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7460 window->assertNoEvents();
7461
7462 // Second finger down on window, the window should receive touch down.
7463 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007464 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007465 .displayId(ADISPLAY_ID_DEFAULT)
7466 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7467 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7468 .x(100)
7469 .y(200))
7470 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7471 .build();
7472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7473 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7474 InputEventInjectionSync::WAIT_FOR_RESULT))
7475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7476
7477 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7478 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7479}
7480
7481/**
7482 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7483 * do not receive key events.
7484 */
7485TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007486 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007487 spy->setFocusable(false);
7488
7489 auto window = createForeground();
7490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7491 setFocusedWindow(window);
7492 window->consumeFocusEvent(true);
7493
7494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7495 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7496 window->consumeKeyDown(ADISPLAY_ID_NONE);
7497
7498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7499 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7500 window->consumeKeyUp(ADISPLAY_ID_NONE);
7501
7502 spy->assertNoEvents();
7503}
7504
Prabir Pradhand65552b2021-10-07 11:23:50 -07007505class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7506public:
7507 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7508 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7509 std::make_shared<FakeApplicationHandle>();
7510 sp<FakeWindowHandle> overlay =
7511 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7512 ADISPLAY_ID_DEFAULT);
7513 overlay->setFocusable(false);
7514 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007515 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007516 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007517 overlay->setTrustedOverlay(true);
7518
7519 std::shared_ptr<FakeApplicationHandle> application =
7520 std::make_shared<FakeApplicationHandle>();
7521 sp<FakeWindowHandle> window =
7522 new FakeWindowHandle(application, mDispatcher, "Application window",
7523 ADISPLAY_ID_DEFAULT);
7524 window->setFocusable(true);
7525 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007526
7527 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7529 setFocusedWindow(window);
7530 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7531 return {std::move(overlay), std::move(window)};
7532 }
7533
7534 void sendFingerEvent(int32_t action) {
7535 NotifyMotionArgs motionArgs =
7536 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7537 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7538 mDispatcher->notifyMotion(&motionArgs);
7539 }
7540
7541 void sendStylusEvent(int32_t action) {
7542 NotifyMotionArgs motionArgs =
7543 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7544 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7545 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7546 mDispatcher->notifyMotion(&motionArgs);
7547 }
7548};
7549
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007550using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7551
7552TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7553 ScopedSilentDeath _silentDeath;
7554
Prabir Pradhand65552b2021-10-07 11:23:50 -07007555 auto [overlay, window] = setupStylusOverlayScenario();
7556 overlay->setTrustedOverlay(false);
7557 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7558 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7559 ".* not a trusted overlay");
7560}
7561
7562TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7563 auto [overlay, window] = setupStylusOverlayScenario();
7564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7565
7566 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7567 overlay->consumeMotionDown();
7568 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7569 overlay->consumeMotionUp();
7570
7571 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7572 window->consumeMotionDown();
7573 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7574 window->consumeMotionUp();
7575
7576 overlay->assertNoEvents();
7577 window->assertNoEvents();
7578}
7579
7580TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7581 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007582 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7584
7585 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7586 overlay->consumeMotionDown();
7587 window->consumeMotionDown();
7588 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7589 overlay->consumeMotionUp();
7590 window->consumeMotionUp();
7591
7592 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7593 window->consumeMotionDown();
7594 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7595 window->consumeMotionUp();
7596
7597 overlay->assertNoEvents();
7598 window->assertNoEvents();
7599}
7600
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007601/**
7602 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7603 * The scenario is as follows:
7604 * - The stylus interceptor overlay is configured as a spy window.
7605 * - The stylus interceptor spy receives the start of a new stylus gesture.
7606 * - It pilfers pointers and then configures itself to no longer be a spy.
7607 * - The stylus interceptor continues to receive the rest of the gesture.
7608 */
7609TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7610 auto [overlay, window] = setupStylusOverlayScenario();
7611 overlay->setSpy(true);
7612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7613
7614 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7615 overlay->consumeMotionDown();
7616 window->consumeMotionDown();
7617
7618 // The interceptor pilfers the pointers.
7619 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7620 window->consumeMotionCancel();
7621
7622 // The interceptor configures itself so that it is no longer a spy.
7623 overlay->setSpy(false);
7624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7625
7626 // It continues to receive the rest of the stylus gesture.
7627 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7628 overlay->consumeMotionMove();
7629 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7630 overlay->consumeMotionUp();
7631
7632 window->assertNoEvents();
7633}
7634
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007635struct User {
7636 int32_t mPid;
7637 int32_t mUid;
7638 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7639 std::unique_ptr<InputDispatcher>& mDispatcher;
7640
7641 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7642 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7643
7644 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7645 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7646 ADISPLAY_ID_DEFAULT, {100, 200},
7647 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7648 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7649 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7650 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7651 }
7652
7653 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7654 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7655 InputEventInjectionSync::WAIT_FOR_RESULT,
7656 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7657 mPolicyFlags);
7658 }
7659
7660 sp<FakeWindowHandle> createWindow() const {
7661 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7662 std::make_shared<FakeApplicationHandle>();
7663 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7664 "Owned Window", ADISPLAY_ID_DEFAULT);
7665 window->setOwnerInfo(mPid, mUid);
7666 return window;
7667 }
7668};
7669
7670using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7671
7672TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7673 auto owner = User(mDispatcher, 10, 11);
7674 auto window = owner.createWindow();
7675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7676
7677 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7678 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7679 window->consumeMotionDown();
7680
7681 setFocusedWindow(window);
7682 window->consumeFocusEvent(true);
7683
7684 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7685 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7686 window->consumeKeyDown(ADISPLAY_ID_NONE);
7687}
7688
7689TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7690 auto owner = User(mDispatcher, 10, 11);
7691 auto window = owner.createWindow();
7692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7693
7694 auto rando = User(mDispatcher, 20, 21);
7695 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7696 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7697
7698 setFocusedWindow(window);
7699 window->consumeFocusEvent(true);
7700
7701 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7702 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7703 window->assertNoEvents();
7704}
7705
7706TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7707 auto owner = User(mDispatcher, 10, 11);
7708 auto window = owner.createWindow();
7709 auto spy = owner.createWindow();
7710 spy->setSpy(true);
7711 spy->setTrustedOverlay(true);
7712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7713
7714 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7715 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7716 spy->consumeMotionDown();
7717 window->consumeMotionDown();
7718}
7719
7720TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7721 auto owner = User(mDispatcher, 10, 11);
7722 auto window = owner.createWindow();
7723
7724 auto rando = User(mDispatcher, 20, 21);
7725 auto randosSpy = rando.createWindow();
7726 randosSpy->setSpy(true);
7727 randosSpy->setTrustedOverlay(true);
7728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7729
7730 // The event is targeted at owner's window, so injection should succeed, but the spy should
7731 // not receive the event.
7732 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7733 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7734 randosSpy->assertNoEvents();
7735 window->consumeMotionDown();
7736}
7737
7738TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7739 auto owner = User(mDispatcher, 10, 11);
7740 auto window = owner.createWindow();
7741
7742 auto rando = User(mDispatcher, 20, 21);
7743 auto randosSpy = rando.createWindow();
7744 randosSpy->setSpy(true);
7745 randosSpy->setTrustedOverlay(true);
7746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7747
7748 // A user that has injection permission can inject into any window.
7749 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7750 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7751 ADISPLAY_ID_DEFAULT));
7752 randosSpy->consumeMotionDown();
7753 window->consumeMotionDown();
7754
7755 setFocusedWindow(randosSpy);
7756 randosSpy->consumeFocusEvent(true);
7757
7758 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7759 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7760 window->assertNoEvents();
7761}
7762
7763TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7764 auto owner = User(mDispatcher, 10, 11);
7765 auto window = owner.createWindow();
7766
7767 auto rando = User(mDispatcher, 20, 21);
7768 auto randosWindow = rando.createWindow();
7769 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7770 randosWindow->setWatchOutsideTouch(true);
7771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7772
7773 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7774 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7775 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7776 window->consumeMotionDown();
7777 randosWindow->consumeMotionOutside();
7778}
7779
Garfield Tane84e6f92019-08-29 17:28:41 -07007780} // namespace android::inputdispatcher