blob: b2575fe025157f6039472d04d30f6483e81d25f6 [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);
136 EXPECT_EQ(motionEvent.getX(0), point.x);
137 EXPECT_EQ(motionEvent.getY(0), point.y);
138 EXPECT_EQ(motionEvent.getRawX(0), point.x);
139 EXPECT_EQ(motionEvent.getRawY(0), point.y);
140 });
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 Nordgrenff0c66e2022-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();
2496 mDisplayInfos.clear();
2497 mWindowInfos.clear();
2498 }
2499
2500 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2501 gui::DisplayInfo info;
2502 info.displayId = displayId;
2503 info.transform = transform;
2504 mDisplayInfos.push_back(std::move(info));
2505 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2506 }
2507
2508 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2509 mWindowInfos.push_back(*windowHandle->getInfo());
2510 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2511 }
2512
2513 // Set up a test scenario where the display has a scaled projection and there are two windows
2514 // on the display.
2515 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2516 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2517 // respectively.
2518 ui::Transform displayTransform;
2519 displayTransform.set(2, 0, 0, 4);
2520 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2521
2522 std::shared_ptr<FakeApplicationHandle> application =
2523 std::make_shared<FakeApplicationHandle>();
2524
2525 // Add two windows to the display. Their frames are represented in the display space.
2526 sp<FakeWindowHandle> firstWindow =
2527 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002528 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2529 addWindow(firstWindow);
2530
2531 sp<FakeWindowHandle> secondWindow =
2532 new FakeWindowHandle(application, mDispatcher, "Second Window",
2533 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002534 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2535 addWindow(secondWindow);
2536 return {std::move(firstWindow), std::move(secondWindow)};
2537 }
2538
2539private:
2540 std::vector<gui::DisplayInfo> mDisplayInfos;
2541 std::vector<gui::WindowInfo> mWindowInfos;
2542};
2543
2544TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2545 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2546 // Send down to the first window. The point is represented in the display space. The point is
2547 // selected so that if the hit test was done with the transform applied to it, then it would
2548 // end up in the incorrect window.
2549 NotifyMotionArgs downMotionArgs =
2550 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2551 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2552 mDispatcher->notifyMotion(&downMotionArgs);
2553
2554 firstWindow->consumeMotionDown();
2555 secondWindow->assertNoEvents();
2556}
2557
2558// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2559// the event should be treated as being in the logical display space.
2560TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2561 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2562 // Send down to the first window. The point is represented in the logical display space. The
2563 // point is selected so that if the hit test was done in logical display space, then it would
2564 // end up in the incorrect window.
2565 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2566 PointF{75 * 2, 55 * 4});
2567
2568 firstWindow->consumeMotionDown();
2569 secondWindow->assertNoEvents();
2570}
2571
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002572// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2573// event should be treated as being in the logical display space.
2574TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2575 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2576
2577 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2578 ui::Transform injectedEventTransform;
2579 injectedEventTransform.set(matrix);
2580 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2581 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2582
2583 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2584 .displayId(ADISPLAY_ID_DEFAULT)
2585 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2586 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2587 .x(untransformedPoint.x)
2588 .y(untransformedPoint.y))
2589 .build();
2590 event.transform(matrix);
2591
2592 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2593 InputEventInjectionSync::WAIT_FOR_RESULT);
2594
2595 firstWindow->consumeMotionDown();
2596 secondWindow->assertNoEvents();
2597}
2598
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002599TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2600 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2601
2602 // Send down to the second window.
2603 NotifyMotionArgs downMotionArgs =
2604 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2605 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2606 mDispatcher->notifyMotion(&downMotionArgs);
2607
2608 firstWindow->assertNoEvents();
2609 const MotionEvent* event = secondWindow->consumeMotion();
2610 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2611
2612 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2613 EXPECT_EQ(300, event->getRawX(0));
2614 EXPECT_EQ(880, event->getRawY(0));
2615
2616 // Ensure that the x and y values are in the window's coordinate space.
2617 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2618 // the logical display space. This will be the origin of the window space.
2619 EXPECT_EQ(100, event->getX(0));
2620 EXPECT_EQ(80, event->getY(0));
2621}
2622
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002623using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2624 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002625
2626class TransferTouchFixture : public InputDispatcherTest,
2627 public ::testing::WithParamInterface<TransferFunction> {};
2628
2629TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002630 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002631
2632 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002633 sp<FakeWindowHandle> firstWindow =
2634 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Arthur Hungba703c32022-12-08 07:45:36 +00002635 firstWindow->setDupTouchToWallpaper(true);
2636
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002637 sp<FakeWindowHandle> secondWindow =
2638 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Arthur Hungba703c32022-12-08 07:45:36 +00002639 sp<FakeWindowHandle> wallpaper =
2640 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
2641 wallpaper->setIsWallpaper(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002642 // Add the windows to the dispatcher
Arthur Hungba703c32022-12-08 07:45:36 +00002643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002644
2645 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002646 NotifyMotionArgs downMotionArgs =
2647 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2648 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002649 mDispatcher->notifyMotion(&downMotionArgs);
Arthur Hungba703c32022-12-08 07:45:36 +00002650
Svet Ganov5d3bc372020-01-26 23:11:07 -08002651 // Only the first window should get the down event
2652 firstWindow->consumeMotionDown();
2653 secondWindow->assertNoEvents();
Arthur Hungba703c32022-12-08 07:45:36 +00002654 wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002655
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002656 // Transfer touch to the second window
2657 TransferFunction f = GetParam();
2658 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2659 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002660 // The first window gets cancel and the second gets down
2661 firstWindow->consumeMotionCancel();
2662 secondWindow->consumeMotionDown();
Arthur Hungba703c32022-12-08 07:45:36 +00002663 wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002664
2665 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002666 NotifyMotionArgs upMotionArgs =
2667 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2668 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002669 mDispatcher->notifyMotion(&upMotionArgs);
2670 // The first window gets no events and the second gets up
2671 firstWindow->assertNoEvents();
2672 secondWindow->consumeMotionUp();
Arthur Hungba703c32022-12-08 07:45:36 +00002673 wallpaper->assertNoEvents();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002674}
2675
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002676/**
2677 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2678 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2679 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2680 * natural to the user.
2681 * In this test, we are sending a pointer to both spy window and first window. We then try to
2682 * transfer touch to the second window. The dispatcher should identify the first window as the
2683 * one that should lose the gesture, and therefore the action should be to move the gesture from
2684 * the first window to the second.
2685 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2686 * the other API, as well.
2687 */
2688TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2690
2691 // Create a couple of windows + a spy window
2692 sp<FakeWindowHandle> spyWindow =
2693 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2694 spyWindow->setTrustedOverlay(true);
2695 spyWindow->setSpy(true);
2696 sp<FakeWindowHandle> firstWindow =
2697 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2698 sp<FakeWindowHandle> secondWindow =
2699 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2700
2701 // Add the windows to the dispatcher
2702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2703
2704 // Send down to the first window
2705 NotifyMotionArgs downMotionArgs =
2706 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2707 ADISPLAY_ID_DEFAULT);
2708 mDispatcher->notifyMotion(&downMotionArgs);
2709 // Only the first window and spy should get the down event
2710 spyWindow->consumeMotionDown();
2711 firstWindow->consumeMotionDown();
2712
2713 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2714 // if f === 'transferTouch'.
2715 TransferFunction f = GetParam();
2716 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2717 ASSERT_TRUE(success);
2718 // The first window gets cancel and the second gets down
2719 firstWindow->consumeMotionCancel();
2720 secondWindow->consumeMotionDown();
2721
2722 // Send up event to the second window
2723 NotifyMotionArgs upMotionArgs =
2724 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2725 ADISPLAY_ID_DEFAULT);
2726 mDispatcher->notifyMotion(&upMotionArgs);
2727 // The first window gets no events and the second+spy get up
2728 firstWindow->assertNoEvents();
2729 spyWindow->consumeMotionUp();
2730 secondWindow->consumeMotionUp();
2731}
2732
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002733TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002735
2736 PointF touchPoint = {10, 10};
2737
2738 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002739 sp<FakeWindowHandle> firstWindow =
2740 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002741 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002742 sp<FakeWindowHandle> secondWindow =
2743 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002744 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002745
2746 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002748
2749 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002750 NotifyMotionArgs downMotionArgs =
2751 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2752 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002753 mDispatcher->notifyMotion(&downMotionArgs);
2754 // Only the first window should get the down event
2755 firstWindow->consumeMotionDown();
2756 secondWindow->assertNoEvents();
2757
2758 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002759 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002760 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002761 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002762 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2763 // Only the first window should get the pointer down event
2764 firstWindow->consumeMotionPointerDown(1);
2765 secondWindow->assertNoEvents();
2766
2767 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002768 TransferFunction f = GetParam();
2769 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2770 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002771 // The first window gets cancel and the second gets down and pointer down
2772 firstWindow->consumeMotionCancel();
2773 secondWindow->consumeMotionDown();
2774 secondWindow->consumeMotionPointerDown(1);
2775
2776 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002777 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002778 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002779 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002780 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2781 // The first window gets nothing and the second gets pointer up
2782 firstWindow->assertNoEvents();
2783 secondWindow->consumeMotionPointerUp(1);
2784
2785 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002786 NotifyMotionArgs upMotionArgs =
2787 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2788 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002789 mDispatcher->notifyMotion(&upMotionArgs);
2790 // The first window gets nothing and the second gets up
2791 firstWindow->assertNoEvents();
2792 secondWindow->consumeMotionUp();
2793}
2794
Arthur Hungba703c32022-12-08 07:45:36 +00002795TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
2796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2797
2798 // Create a couple of windows
2799 sp<FakeWindowHandle> firstWindow =
2800 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2801 ADISPLAY_ID_DEFAULT);
2802 firstWindow->setDupTouchToWallpaper(true);
2803 sp<FakeWindowHandle> secondWindow =
2804 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2805 ADISPLAY_ID_DEFAULT);
2806 secondWindow->setDupTouchToWallpaper(true);
2807
2808 sp<FakeWindowHandle> wallpaper1 =
2809 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
2810 wallpaper1->setIsWallpaper(true);
2811
2812 sp<FakeWindowHandle> wallpaper2 =
2813 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
2814 wallpaper2->setIsWallpaper(true);
2815 // Add the windows to the dispatcher
2816 mDispatcher->setInputWindows(
2817 {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
2818
2819 // Send down to the first window
2820 NotifyMotionArgs downMotionArgs =
2821 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2822 ADISPLAY_ID_DEFAULT);
2823 mDispatcher->notifyMotion(&downMotionArgs);
2824
2825 // Only the first window should get the down event
2826 firstWindow->consumeMotionDown();
2827 secondWindow->assertNoEvents();
2828 wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2829 wallpaper2->assertNoEvents();
2830
2831 // Transfer touch focus to the second window
2832 TransferFunction f = GetParam();
2833 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2834 ASSERT_TRUE(success);
2835
2836 // The first window gets cancel and the second gets down
2837 firstWindow->consumeMotionCancel();
2838 secondWindow->consumeMotionDown();
2839 wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2840 wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2841
2842 // Send up event to the second window
2843 NotifyMotionArgs upMotionArgs =
2844 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2845 ADISPLAY_ID_DEFAULT);
2846 mDispatcher->notifyMotion(&upMotionArgs);
2847 // The first window gets no events and the second gets up
2848 firstWindow->assertNoEvents();
2849 secondWindow->consumeMotionUp();
2850 wallpaper1->assertNoEvents();
2851 wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
2852}
2853
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002854// For the cases of single pointer touch and two pointers non-split touch, the api's
2855// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2856// for the case where there are multiple pointers split across several windows.
2857INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2858 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002859 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2860 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002861 return dispatcher->transferTouch(destChannelToken,
2862 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002863 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002864 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2865 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002866 return dispatcher->transferTouchFocus(from, to,
2867 false /*isDragAndDrop*/);
2868 }));
2869
Svet Ganov5d3bc372020-01-26 23:11:07 -08002870TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002871 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002872
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002873 sp<FakeWindowHandle> firstWindow =
2874 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002875 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002876
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002877 sp<FakeWindowHandle> secondWindow =
2878 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002879 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002880
2881 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002883
2884 PointF pointInFirst = {300, 200};
2885 PointF pointInSecond = {300, 600};
2886
2887 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002888 NotifyMotionArgs firstDownMotionArgs =
2889 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2890 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002891 mDispatcher->notifyMotion(&firstDownMotionArgs);
2892 // Only the first window should get the down event
2893 firstWindow->consumeMotionDown();
2894 secondWindow->assertNoEvents();
2895
2896 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002897 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002898 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002899 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002900 mDispatcher->notifyMotion(&secondDownMotionArgs);
2901 // The first window gets a move and the second a down
2902 firstWindow->consumeMotionMove();
2903 secondWindow->consumeMotionDown();
2904
2905 // Transfer touch focus to the second window
2906 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2907 // The first window gets cancel and the new gets pointer down (it already saw down)
2908 firstWindow->consumeMotionCancel();
2909 secondWindow->consumeMotionPointerDown(1);
2910
2911 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002912 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002913 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002914 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002915 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2916 // The first window gets nothing and the second gets pointer up
2917 firstWindow->assertNoEvents();
2918 secondWindow->consumeMotionPointerUp(1);
2919
2920 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002921 NotifyMotionArgs upMotionArgs =
2922 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2923 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002924 mDispatcher->notifyMotion(&upMotionArgs);
2925 // The first window gets nothing and the second gets up
2926 firstWindow->assertNoEvents();
2927 secondWindow->consumeMotionUp();
2928}
2929
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002930// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2931// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2932// touch is not supported, so the touch should continue on those windows and the transferred-to
2933// window should get nothing.
2934TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2936
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002937 sp<FakeWindowHandle> firstWindow =
2938 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2939 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002940
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002941 sp<FakeWindowHandle> secondWindow =
2942 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2943 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002944
2945 // Add the windows to the dispatcher
2946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2947
2948 PointF pointInFirst = {300, 200};
2949 PointF pointInSecond = {300, 600};
2950
2951 // Send down to the first window
2952 NotifyMotionArgs firstDownMotionArgs =
2953 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2954 ADISPLAY_ID_DEFAULT, {pointInFirst});
2955 mDispatcher->notifyMotion(&firstDownMotionArgs);
2956 // Only the first window should get the down event
2957 firstWindow->consumeMotionDown();
2958 secondWindow->assertNoEvents();
2959
2960 // Send down to the second window
2961 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002962 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002963 {pointInFirst, pointInSecond});
2964 mDispatcher->notifyMotion(&secondDownMotionArgs);
2965 // The first window gets a move and the second a down
2966 firstWindow->consumeMotionMove();
2967 secondWindow->consumeMotionDown();
2968
2969 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002970 const bool transferred =
2971 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002972 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2973 ASSERT_FALSE(transferred);
2974 firstWindow->assertNoEvents();
2975 secondWindow->assertNoEvents();
2976
2977 // The rest of the dispatch should proceed as normal
2978 // Send pointer up to the second window
2979 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002980 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002981 {pointInFirst, pointInSecond});
2982 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2983 // The first window gets MOVE and the second gets pointer up
2984 firstWindow->consumeMotionMove();
2985 secondWindow->consumeMotionUp();
2986
2987 // Send up event to the first window
2988 NotifyMotionArgs upMotionArgs =
2989 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2990 ADISPLAY_ID_DEFAULT);
2991 mDispatcher->notifyMotion(&upMotionArgs);
2992 // The first window gets nothing and the second gets up
2993 firstWindow->consumeMotionUp();
2994 secondWindow->assertNoEvents();
2995}
2996
Arthur Hungabbb9d82021-09-01 14:52:30 +00002997// This case will create two windows and one mirrored window on the default display and mirror
2998// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2999// the windows info of second display before default display.
3000TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
3001 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3002 sp<FakeWindowHandle> firstWindowInPrimary =
3003 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
3004 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003005 sp<FakeWindowHandle> secondWindowInPrimary =
3006 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3007 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003008
3009 sp<FakeWindowHandle> mirrorWindowInPrimary =
3010 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3011 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003012
3013 sp<FakeWindowHandle> firstWindowInSecondary =
3014 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3015 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003016
3017 sp<FakeWindowHandle> secondWindowInSecondary =
3018 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3019 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003020
3021 // Update window info, let it find window handle of second display first.
3022 mDispatcher->setInputWindows(
3023 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3024 {ADISPLAY_ID_DEFAULT,
3025 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3026
3027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3028 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3029 {50, 50}))
3030 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3031
3032 // Window should receive motion event.
3033 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3034
3035 // Transfer touch focus
3036 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
3037 secondWindowInPrimary->getToken()));
3038 // The first window gets cancel.
3039 firstWindowInPrimary->consumeMotionCancel();
3040 secondWindowInPrimary->consumeMotionDown();
3041
3042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3043 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3044 ADISPLAY_ID_DEFAULT, {150, 50}))
3045 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3046 firstWindowInPrimary->assertNoEvents();
3047 secondWindowInPrimary->consumeMotionMove();
3048
3049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3050 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3051 {150, 50}))
3052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3053 firstWindowInPrimary->assertNoEvents();
3054 secondWindowInPrimary->consumeMotionUp();
3055}
3056
3057// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
3058// 'transferTouch' api.
3059TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
3060 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3061 sp<FakeWindowHandle> firstWindowInPrimary =
3062 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
3063 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003064 sp<FakeWindowHandle> secondWindowInPrimary =
3065 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3066 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003067
3068 sp<FakeWindowHandle> mirrorWindowInPrimary =
3069 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
3070 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003071
3072 sp<FakeWindowHandle> firstWindowInSecondary =
3073 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3074 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003075
3076 sp<FakeWindowHandle> secondWindowInSecondary =
3077 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
3078 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003079
3080 // Update window info, let it find window handle of second display first.
3081 mDispatcher->setInputWindows(
3082 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
3083 {ADISPLAY_ID_DEFAULT,
3084 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
3085
3086 // Touch on second display.
3087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3088 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
3089 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3090
3091 // Window should receive motion event.
3092 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3093
3094 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07003095 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00003096
3097 // The first window gets cancel.
3098 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
3099 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
3100
3101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3102 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3103 SECOND_DISPLAY_ID, {150, 50}))
3104 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3105 firstWindowInPrimary->assertNoEvents();
3106 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3107
3108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3109 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3111 firstWindowInPrimary->assertNoEvents();
3112 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3113}
3114
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003115TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003116 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003117 sp<FakeWindowHandle> window =
3118 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3119
Vishnu Nair47074b82020-08-14 11:54:47 -07003120 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003122 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123
3124 window->consumeFocusEvent(true);
3125
3126 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3127 mDispatcher->notifyKey(&keyArgs);
3128
3129 // Window should receive key down event.
3130 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3131}
3132
3133TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003134 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003135 sp<FakeWindowHandle> window =
3136 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3137
Arthur Hung72d8dc32020-03-28 00:48:39 +00003138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003139
3140 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3141 mDispatcher->notifyKey(&keyArgs);
3142 mDispatcher->waitForIdle();
3143
3144 window->assertNoEvents();
3145}
3146
3147// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3148TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003149 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003150 sp<FakeWindowHandle> window =
3151 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3152
Arthur Hung72d8dc32020-03-28 00:48:39 +00003153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003154
3155 // Send key
3156 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3157 mDispatcher->notifyKey(&keyArgs);
3158 // Send motion
3159 NotifyMotionArgs motionArgs =
3160 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3161 ADISPLAY_ID_DEFAULT);
3162 mDispatcher->notifyMotion(&motionArgs);
3163
3164 // Window should receive only the motion event
3165 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3166 window->assertNoEvents(); // Key event or focus event will not be received
3167}
3168
arthurhungea3f4fc2020-12-21 23:18:53 +08003169TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3170 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3171
arthurhungea3f4fc2020-12-21 23:18:53 +08003172 sp<FakeWindowHandle> firstWindow =
3173 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3174 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003175
arthurhungea3f4fc2020-12-21 23:18:53 +08003176 sp<FakeWindowHandle> secondWindow =
3177 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3178 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003179
3180 // Add the windows to the dispatcher
3181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3182
3183 PointF pointInFirst = {300, 200};
3184 PointF pointInSecond = {300, 600};
3185
3186 // Send down to the first window
3187 NotifyMotionArgs firstDownMotionArgs =
3188 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3189 ADISPLAY_ID_DEFAULT, {pointInFirst});
3190 mDispatcher->notifyMotion(&firstDownMotionArgs);
3191 // Only the first window should get the down event
3192 firstWindow->consumeMotionDown();
3193 secondWindow->assertNoEvents();
3194
3195 // Send down to the second window
3196 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003197 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003198 {pointInFirst, pointInSecond});
3199 mDispatcher->notifyMotion(&secondDownMotionArgs);
3200 // The first window gets a move and the second a down
3201 firstWindow->consumeMotionMove();
3202 secondWindow->consumeMotionDown();
3203
3204 // Send pointer cancel to the second window
3205 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003206 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003207 {pointInFirst, pointInSecond});
3208 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3209 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3210 // The first window gets move and the second gets cancel.
3211 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3212 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3213
3214 // Send up event.
3215 NotifyMotionArgs upMotionArgs =
3216 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3217 ADISPLAY_ID_DEFAULT);
3218 mDispatcher->notifyMotion(&upMotionArgs);
3219 // The first window gets up and the second gets nothing.
3220 firstWindow->consumeMotionUp();
3221 secondWindow->assertNoEvents();
3222}
3223
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003224TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3226
3227 sp<FakeWindowHandle> window =
3228 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3230 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3231 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3232 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3233
3234 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3235 window->assertNoEvents();
3236 mDispatcher->waitForIdle();
3237}
3238
chaviwd1c23182019-12-20 18:44:56 -08003239class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003240public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003241 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003242 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003243 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003244 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003245 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003246 }
3247
chaviwd1c23182019-12-20 18:44:56 -08003248 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3249
3250 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3251 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3252 expectedDisplayId, expectedFlags);
3253 }
3254
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003255 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3256
3257 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3258
chaviwd1c23182019-12-20 18:44:56 -08003259 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3260 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3261 expectedDisplayId, expectedFlags);
3262 }
3263
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003264 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3265 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3266 expectedDisplayId, expectedFlags);
3267 }
3268
chaviwd1c23182019-12-20 18:44:56 -08003269 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3270 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3271 expectedDisplayId, expectedFlags);
3272 }
3273
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003274 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3275 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3276 expectedDisplayId, expectedFlags);
3277 }
3278
Arthur Hungfbfa5722021-11-16 02:45:54 +00003279 void consumeMotionPointerDown(int32_t pointerIdx) {
3280 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3281 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3282 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3283 0 /*expectedFlags*/);
3284 }
3285
Evan Rosky84f07f02021-04-16 10:42:42 -07003286 MotionEvent* consumeMotion() {
3287 InputEvent* event = mInputReceiver->consume();
3288 if (!event) {
3289 ADD_FAILURE() << "No event was produced";
3290 return nullptr;
3291 }
3292 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3293 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3294 return nullptr;
3295 }
3296 return static_cast<MotionEvent*>(event);
3297 }
3298
chaviwd1c23182019-12-20 18:44:56 -08003299 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3300
3301private:
3302 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003303};
3304
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003305using InputDispatcherMonitorTest = InputDispatcherTest;
3306
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003307/**
3308 * Two entities that receive touch: A window, and a global monitor.
3309 * The touch goes to the window, and then the window disappears.
3310 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3311 * for the monitor, as well.
3312 * 1. foregroundWindow
3313 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3314 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003315TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003316 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3317 sp<FakeWindowHandle> window =
3318 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3319
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003320 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003321
3322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3324 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3325 {100, 200}))
3326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3327
3328 // Both the foreground window and the global monitor should receive the touch down
3329 window->consumeMotionDown();
3330 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3331
3332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3333 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3334 ADISPLAY_ID_DEFAULT, {110, 200}))
3335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3336
3337 window->consumeMotionMove();
3338 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3339
3340 // Now the foreground window goes away
3341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3342 window->consumeMotionCancel();
3343 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3344
3345 // If more events come in, there will be no more foreground window to send them to. This will
3346 // cause a cancel for the monitor, as well.
3347 ASSERT_EQ(InputEventInjectionResult::FAILED,
3348 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3349 ADISPLAY_ID_DEFAULT, {120, 200}))
3350 << "Injection should fail because the window was removed";
3351 window->assertNoEvents();
3352 // Global monitor now gets the cancel
3353 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3354}
3355
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003356TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003357 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003358 sp<FakeWindowHandle> window =
3359 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003361
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003362 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003363
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003364 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003365 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003366 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003367 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003368 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003369}
3370
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003371TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3372 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003373
Chris Yea209fde2020-07-22 13:54:51 -07003374 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003375 sp<FakeWindowHandle> window =
3376 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003382 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003383 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003384
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003385 // Pilfer pointers from the monitor.
3386 // This should not do anything and the window should continue to receive events.
3387 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003388
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003390 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3391 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003392 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003393
3394 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3395 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003396}
3397
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003398TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003399 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3400 sp<FakeWindowHandle> window =
3401 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3403 window->setWindowOffset(20, 40);
3404 window->setWindowTransform(0, 1, -1, 0);
3405
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003406 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003407
3408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3411 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3412 MotionEvent* event = monitor.consumeMotion();
3413 // Even though window has transform, gesture monitor must not.
3414 ASSERT_EQ(ui::Transform(), event->getTransform());
3415}
3416
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003417TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003418 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003419 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003420
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003421 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003422 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003423 << "Injection should fail if there is a monitor, but no touchable window";
3424 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003425}
3426
chaviw81e2bb92019-12-18 15:03:51 -08003427TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003428 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003429 sp<FakeWindowHandle> window =
3430 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3431
Arthur Hung72d8dc32020-03-28 00:48:39 +00003432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003433
3434 NotifyMotionArgs motionArgs =
3435 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3436 ADISPLAY_ID_DEFAULT);
3437
3438 mDispatcher->notifyMotion(&motionArgs);
3439 // Window should receive motion down event.
3440 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3441
3442 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003443 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003444 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3445 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3446 motionArgs.pointerCoords[0].getX() - 10);
3447
3448 mDispatcher->notifyMotion(&motionArgs);
3449 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3450 0 /*expectedFlags*/);
3451}
3452
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003453/**
3454 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3455 * the device default right away. In the test scenario, we check both the default value,
3456 * and the action of enabling / disabling.
3457 */
3458TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003459 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003460 sp<FakeWindowHandle> window =
3461 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003462 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003463
3464 // Set focused application.
3465 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003466 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003467
3468 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003470 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003471 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3472
3473 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003474 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003476 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3477
3478 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003479 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3480 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003481 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003482 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003483 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003484 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003485 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3486
3487 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003488 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003490 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3491
3492 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003493 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3494 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003495 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003496 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003498 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003499 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3500
3501 window->assertNoEvents();
3502}
3503
Gang Wange9087892020-01-07 12:17:14 -05003504TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003505 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003506 sp<FakeWindowHandle> window =
3507 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3508
3509 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003510 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003511
Arthur Hung72d8dc32020-03-28 00:48:39 +00003512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003513 setFocusedWindow(window);
3514
Gang Wange9087892020-01-07 12:17:14 -05003515 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3516
3517 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3518 mDispatcher->notifyKey(&keyArgs);
3519
3520 InputEvent* event = window->consume();
3521 ASSERT_NE(event, nullptr);
3522
3523 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3524 ASSERT_NE(verified, nullptr);
3525 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3526
3527 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3528 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3529 ASSERT_EQ(keyArgs.source, verified->source);
3530 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3531
3532 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3533
3534 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003535 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003536 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003537 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3538 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3539 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3540 ASSERT_EQ(0, verifiedKey.repeatCount);
3541}
3542
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003543TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003544 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003545 sp<FakeWindowHandle> window =
3546 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3547
3548 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3549
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003550 ui::Transform transform;
3551 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3552
3553 gui::DisplayInfo displayInfo;
3554 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3555 displayInfo.transform = transform;
3556
3557 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003558
3559 NotifyMotionArgs motionArgs =
3560 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3561 ADISPLAY_ID_DEFAULT);
3562 mDispatcher->notifyMotion(&motionArgs);
3563
3564 InputEvent* event = window->consume();
3565 ASSERT_NE(event, nullptr);
3566
3567 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3568 ASSERT_NE(verified, nullptr);
3569 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3570
3571 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3572 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3573 EXPECT_EQ(motionArgs.source, verified->source);
3574 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3575
3576 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3577
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003578 const vec2 rawXY =
3579 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3580 motionArgs.pointerCoords[0].getXYValue());
3581 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3582 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003583 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003584 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003585 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003586 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3587 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3588}
3589
chaviw09c8d2d2020-08-24 15:48:26 -07003590/**
3591 * Ensure that separate calls to sign the same data are generating the same key.
3592 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3593 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3594 * tests.
3595 */
3596TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3597 KeyEvent event = getTestKeyEvent();
3598 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3599
3600 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3601 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3602 ASSERT_EQ(hmac1, hmac2);
3603}
3604
3605/**
3606 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3607 */
3608TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3609 KeyEvent event = getTestKeyEvent();
3610 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3611 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3612
3613 verifiedEvent.deviceId += 1;
3614 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3615
3616 verifiedEvent.source += 1;
3617 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3618
3619 verifiedEvent.eventTimeNanos += 1;
3620 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3621
3622 verifiedEvent.displayId += 1;
3623 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3624
3625 verifiedEvent.action += 1;
3626 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3627
3628 verifiedEvent.downTimeNanos += 1;
3629 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3630
3631 verifiedEvent.flags += 1;
3632 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3633
3634 verifiedEvent.keyCode += 1;
3635 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3636
3637 verifiedEvent.scanCode += 1;
3638 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3639
3640 verifiedEvent.metaState += 1;
3641 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3642
3643 verifiedEvent.repeatCount += 1;
3644 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3645}
3646
Vishnu Nair958da932020-08-21 17:12:37 -07003647TEST_F(InputDispatcherTest, SetFocusedWindow) {
3648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3649 sp<FakeWindowHandle> windowTop =
3650 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3651 sp<FakeWindowHandle> windowSecond =
3652 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3653 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3654
3655 // Top window is also focusable but is not granted focus.
3656 windowTop->setFocusable(true);
3657 windowSecond->setFocusable(true);
3658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3659 setFocusedWindow(windowSecond);
3660
3661 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3663 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003664
3665 // Focused window should receive event.
3666 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3667 windowTop->assertNoEvents();
3668}
3669
3670TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3671 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3672 sp<FakeWindowHandle> window =
3673 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3674 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3675
3676 window->setFocusable(true);
3677 // Release channel for window is no longer valid.
3678 window->releaseChannel();
3679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3680 setFocusedWindow(window);
3681
3682 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003683 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3684 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003685
3686 // window channel is invalid, so it should not receive any input event.
3687 window->assertNoEvents();
3688}
3689
3690TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3691 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3692 sp<FakeWindowHandle> window =
3693 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003694 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003695 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3696
Vishnu Nair958da932020-08-21 17:12:37 -07003697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3698 setFocusedWindow(window);
3699
3700 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003701 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3702 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003703
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003704 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003705 window->assertNoEvents();
3706}
3707
3708TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3710 sp<FakeWindowHandle> windowTop =
3711 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3712 sp<FakeWindowHandle> windowSecond =
3713 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3714 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3715
3716 windowTop->setFocusable(true);
3717 windowSecond->setFocusable(true);
3718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3719 setFocusedWindow(windowTop);
3720 windowTop->consumeFocusEvent(true);
3721
3722 setFocusedWindow(windowSecond, windowTop);
3723 windowSecond->consumeFocusEvent(true);
3724 windowTop->consumeFocusEvent(false);
3725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3727 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003728
3729 // Focused window should receive event.
3730 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3731}
3732
3733TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3735 sp<FakeWindowHandle> windowTop =
3736 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3737 sp<FakeWindowHandle> windowSecond =
3738 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3739 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3740
3741 windowTop->setFocusable(true);
3742 windowSecond->setFocusable(true);
3743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3744 setFocusedWindow(windowSecond, windowTop);
3745
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3747 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003748
3749 // Event should be dropped.
3750 windowTop->assertNoEvents();
3751 windowSecond->assertNoEvents();
3752}
3753
3754TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3756 sp<FakeWindowHandle> window =
3757 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3758 sp<FakeWindowHandle> previousFocusedWindow =
3759 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3760 ADISPLAY_ID_DEFAULT);
3761 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3762
3763 window->setFocusable(true);
3764 previousFocusedWindow->setFocusable(true);
3765 window->setVisible(false);
3766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3767 setFocusedWindow(previousFocusedWindow);
3768 previousFocusedWindow->consumeFocusEvent(true);
3769
3770 // Requesting focus on invisible window takes focus from currently focused window.
3771 setFocusedWindow(window);
3772 previousFocusedWindow->consumeFocusEvent(false);
3773
3774 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003776 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003777 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003778
3779 // Window does not get focus event or key down.
3780 window->assertNoEvents();
3781
3782 // Window becomes visible.
3783 window->setVisible(true);
3784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3785
3786 // Window receives focus event.
3787 window->consumeFocusEvent(true);
3788 // Focused window receives key down.
3789 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3790}
3791
Vishnu Nair599f1412021-06-21 10:39:58 -07003792TEST_F(InputDispatcherTest, DisplayRemoved) {
3793 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3794 sp<FakeWindowHandle> window =
3795 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3796 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3797
3798 // window is granted focus.
3799 window->setFocusable(true);
3800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3801 setFocusedWindow(window);
3802 window->consumeFocusEvent(true);
3803
3804 // When a display is removed window loses focus.
3805 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3806 window->consumeFocusEvent(false);
3807}
3808
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003809/**
3810 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3811 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3812 * of the 'slipperyEnterWindow'.
3813 *
3814 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3815 * a way so that the touched location is no longer covered by the top window.
3816 *
3817 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3818 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3819 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3820 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3821 * with ACTION_DOWN).
3822 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3823 * window moved itself away from the touched location and had Flag::SLIPPERY.
3824 *
3825 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3826 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3827 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3828 *
3829 * In this test, we ensure that the event received by the bottom window has
3830 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3831 */
3832TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00003833 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3834 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003835
3836 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3837 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3838
3839 sp<FakeWindowHandle> slipperyExitWindow =
3840 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003841 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003842 // Make sure this one overlaps the bottom window
3843 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3844 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3845 // one. Windows with the same owner are not considered to be occluding each other.
3846 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3847
3848 sp<FakeWindowHandle> slipperyEnterWindow =
3849 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3850 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3851
3852 mDispatcher->setInputWindows(
3853 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3854
3855 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3856 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3857 ADISPLAY_ID_DEFAULT, {{50, 50}});
3858 mDispatcher->notifyMotion(&args);
3859 slipperyExitWindow->consumeMotionDown();
3860 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3861 mDispatcher->setInputWindows(
3862 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3863
3864 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3865 ADISPLAY_ID_DEFAULT, {{51, 51}});
3866 mDispatcher->notifyMotion(&args);
3867
3868 slipperyExitWindow->consumeMotionCancel();
3869
3870 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3871 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3872}
3873
Garfield Tan1c7bc862020-01-28 13:24:04 -08003874class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3875protected:
3876 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3877 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3878
Chris Yea209fde2020-07-22 13:54:51 -07003879 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003880 sp<FakeWindowHandle> mWindow;
3881
3882 virtual void SetUp() override {
3883 mFakePolicy = new FakeInputDispatcherPolicy();
3884 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003885 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003886 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3887 ASSERT_EQ(OK, mDispatcher->start());
3888
3889 setUpWindow();
3890 }
3891
3892 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003893 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003894 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3895
Vishnu Nair47074b82020-08-14 11:54:47 -07003896 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003898 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003899 mWindow->consumeFocusEvent(true);
3900 }
3901
Chris Ye2ad95392020-09-01 13:44:44 -07003902 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003903 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003904 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003905 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3906 mDispatcher->notifyKey(&keyArgs);
3907
3908 // Window should receive key down event.
3909 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3910 }
3911
3912 void expectKeyRepeatOnce(int32_t repeatCount) {
3913 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3914 InputEvent* repeatEvent = mWindow->consume();
3915 ASSERT_NE(nullptr, repeatEvent);
3916
3917 uint32_t eventType = repeatEvent->getType();
3918 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3919
3920 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3921 uint32_t eventAction = repeatKeyEvent->getAction();
3922 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3923 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3924 }
3925
Chris Ye2ad95392020-09-01 13:44:44 -07003926 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003927 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003928 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003929 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3930 mDispatcher->notifyKey(&keyArgs);
3931
3932 // Window should receive key down event.
3933 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3934 0 /*expectedFlags*/);
3935 }
3936};
3937
3938TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003939 sendAndConsumeKeyDown(1 /* deviceId */);
3940 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3941 expectKeyRepeatOnce(repeatCount);
3942 }
3943}
3944
3945TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3946 sendAndConsumeKeyDown(1 /* deviceId */);
3947 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3948 expectKeyRepeatOnce(repeatCount);
3949 }
3950 sendAndConsumeKeyDown(2 /* deviceId */);
3951 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003952 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3953 expectKeyRepeatOnce(repeatCount);
3954 }
3955}
3956
3957TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003958 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003959 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003960 sendAndConsumeKeyUp(1 /* deviceId */);
3961 mWindow->assertNoEvents();
3962}
3963
3964TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3965 sendAndConsumeKeyDown(1 /* deviceId */);
3966 expectKeyRepeatOnce(1 /*repeatCount*/);
3967 sendAndConsumeKeyDown(2 /* deviceId */);
3968 expectKeyRepeatOnce(1 /*repeatCount*/);
3969 // Stale key up from device 1.
3970 sendAndConsumeKeyUp(1 /* deviceId */);
3971 // Device 2 is still down, keep repeating
3972 expectKeyRepeatOnce(2 /*repeatCount*/);
3973 expectKeyRepeatOnce(3 /*repeatCount*/);
3974 // Device 2 key up
3975 sendAndConsumeKeyUp(2 /* deviceId */);
3976 mWindow->assertNoEvents();
3977}
3978
3979TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3980 sendAndConsumeKeyDown(1 /* deviceId */);
3981 expectKeyRepeatOnce(1 /*repeatCount*/);
3982 sendAndConsumeKeyDown(2 /* deviceId */);
3983 expectKeyRepeatOnce(1 /*repeatCount*/);
3984 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3985 sendAndConsumeKeyUp(2 /* deviceId */);
3986 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003987 mWindow->assertNoEvents();
3988}
3989
liushenxiang42232912021-05-21 20:24:09 +08003990TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3991 sendAndConsumeKeyDown(DEVICE_ID);
3992 expectKeyRepeatOnce(1 /*repeatCount*/);
3993 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3994 mDispatcher->notifyDeviceReset(&args);
3995 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3996 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3997 mWindow->assertNoEvents();
3998}
3999
Garfield Tan1c7bc862020-01-28 13:24:04 -08004000TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07004001 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004002 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4003 InputEvent* repeatEvent = mWindow->consume();
4004 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4005 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
4006 IdGenerator::getSource(repeatEvent->getId()));
4007 }
4008}
4009
4010TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07004011 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08004012
4013 std::unordered_set<int32_t> idSet;
4014 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
4015 InputEvent* repeatEvent = mWindow->consume();
4016 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
4017 int32_t id = repeatEvent->getId();
4018 EXPECT_EQ(idSet.end(), idSet.find(id));
4019 idSet.insert(id);
4020 }
4021}
4022
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004023/* Test InputDispatcher for MultiDisplay */
4024class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
4025public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004026 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004027 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08004028
Chris Yea209fde2020-07-22 13:54:51 -07004029 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004030 windowInPrimary =
4031 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004032
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004033 // Set focus window for primary display, but focused display would be second one.
4034 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07004035 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004037 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004038 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08004039
Chris Yea209fde2020-07-22 13:54:51 -07004040 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004041 windowInSecondary =
4042 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004043 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004044 // Set focus display to second one.
4045 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
4046 // Set focus window for second display.
4047 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07004048 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004049 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004050 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004051 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004052 }
4053
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004054 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004055 InputDispatcherTest::TearDown();
4056
Chris Yea209fde2020-07-22 13:54:51 -07004057 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004058 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07004059 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004060 windowInSecondary.clear();
4061 }
4062
4063protected:
Chris Yea209fde2020-07-22 13:54:51 -07004064 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004065 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07004066 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004067 sp<FakeWindowHandle> windowInSecondary;
4068};
4069
4070TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
4071 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4073 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004075 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08004076 windowInSecondary->assertNoEvents();
4077
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004078 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4080 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004082 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004083 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08004084}
4085
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004086TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004087 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4089 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004090 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004091 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08004092 windowInSecondary->assertNoEvents();
4093
4094 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08004097 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004098 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08004099
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004100 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004101 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004102
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004103 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004104 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4105 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004106
4107 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004108 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004109 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004110 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004111 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 windowInSecondary->assertNoEvents();
4113}
4114
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004115// Test per-display input monitors for motion event.
4116TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004117 FakeMonitorReceiver monitorInPrimary =
4118 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4119 FakeMonitorReceiver monitorInSecondary =
4120 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004121
4122 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4124 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004126 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004127 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004128 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004129 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004130
4131 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4133 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4134 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004135 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004136 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004137 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004138 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004139
4140 // Test inject a non-pointer motion event.
4141 // If specific a display, it will dispatch to the focused window of particular display,
4142 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4144 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004146 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004147 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004148 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004149 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004150}
4151
4152// Test per-display input monitors for key event.
4153TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004154 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004155 FakeMonitorReceiver monitorInPrimary =
4156 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4157 FakeMonitorReceiver monitorInSecondary =
4158 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004159
4160 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4162 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004163 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004164 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004165 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004166 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004167}
4168
Vishnu Nair958da932020-08-21 17:12:37 -07004169TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4170 sp<FakeWindowHandle> secondWindowInPrimary =
4171 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
4172 secondWindowInPrimary->setFocusable(true);
4173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4174 setFocusedWindow(secondWindowInPrimary);
4175 windowInPrimary->consumeFocusEvent(false);
4176 secondWindowInPrimary->consumeFocusEvent(true);
4177
4178 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4180 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004181 windowInPrimary->assertNoEvents();
4182 windowInSecondary->assertNoEvents();
4183 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4184}
4185
Arthur Hungdfd528e2021-12-08 13:23:04 +00004186TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4187 FakeMonitorReceiver monitorInPrimary =
4188 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4189 FakeMonitorReceiver monitorInSecondary =
4190 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4191
4192 // Test touch down on primary display.
4193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4194 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4195 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4196 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4197 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4198
4199 // Test touch down on second display.
4200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4202 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4203 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4204 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4205
4206 // Trigger cancel touch.
4207 mDispatcher->cancelCurrentTouch();
4208 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4209 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4210 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4211 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4212
4213 // Test inject a move motion event, no window/monitor should receive the event.
4214 ASSERT_EQ(InputEventInjectionResult::FAILED,
4215 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4216 ADISPLAY_ID_DEFAULT, {110, 200}))
4217 << "Inject motion event should return InputEventInjectionResult::FAILED";
4218 windowInPrimary->assertNoEvents();
4219 monitorInPrimary.assertNoEvents();
4220
4221 ASSERT_EQ(InputEventInjectionResult::FAILED,
4222 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4223 SECOND_DISPLAY_ID, {110, 200}))
4224 << "Inject motion event should return InputEventInjectionResult::FAILED";
4225 windowInSecondary->assertNoEvents();
4226 monitorInSecondary.assertNoEvents();
4227}
4228
Jackal Guof9696682018-10-05 12:23:23 +08004229class InputFilterTest : public InputDispatcherTest {
4230protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004231 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4232 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004233 NotifyMotionArgs motionArgs;
4234
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004235 motionArgs =
4236 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004237 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004238 motionArgs =
4239 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004240 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004241 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004242 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004243 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4244 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004245 } else {
4246 mFakePolicy->assertFilterInputEventWasNotCalled();
4247 }
4248 }
4249
4250 void testNotifyKey(bool expectToBeFiltered) {
4251 NotifyKeyArgs keyArgs;
4252
4253 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4254 mDispatcher->notifyKey(&keyArgs);
4255 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4256 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004257 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004258
4259 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004260 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004261 } else {
4262 mFakePolicy->assertFilterInputEventWasNotCalled();
4263 }
4264 }
4265};
4266
4267// Test InputFilter for MotionEvent
4268TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4269 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4270 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4271 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4272
4273 // Enable InputFilter
4274 mDispatcher->setInputFilterEnabled(true);
4275 // Test touch on both primary and second display, and check if both events are filtered.
4276 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4277 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4278
4279 // Disable InputFilter
4280 mDispatcher->setInputFilterEnabled(false);
4281 // Test touch on both primary and second display, and check if both events aren't filtered.
4282 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4283 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4284}
4285
4286// Test InputFilter for KeyEvent
4287TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4288 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4289 testNotifyKey(/*expectToBeFiltered*/ false);
4290
4291 // Enable InputFilter
4292 mDispatcher->setInputFilterEnabled(true);
4293 // Send a key event, and check if it is filtered.
4294 testNotifyKey(/*expectToBeFiltered*/ true);
4295
4296 // Disable InputFilter
4297 mDispatcher->setInputFilterEnabled(false);
4298 // Send a key event, and check if it isn't filtered.
4299 testNotifyKey(/*expectToBeFiltered*/ false);
4300}
4301
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004302// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4303// logical display coordinate space.
4304TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4305 ui::Transform firstDisplayTransform;
4306 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4307 ui::Transform secondDisplayTransform;
4308 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4309
4310 std::vector<gui::DisplayInfo> displayInfos(2);
4311 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4312 displayInfos[0].transform = firstDisplayTransform;
4313 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4314 displayInfos[1].transform = secondDisplayTransform;
4315
4316 mDispatcher->onWindowInfosChanged({}, displayInfos);
4317
4318 // Enable InputFilter
4319 mDispatcher->setInputFilterEnabled(true);
4320
4321 // Ensure the correct transforms are used for the displays.
4322 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4323 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4324}
4325
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004326class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4327protected:
4328 virtual void SetUp() override {
4329 InputDispatcherTest::SetUp();
4330
4331 /**
4332 * We don't need to enable input filter to test the injected event policy, but we enabled it
4333 * here to make the tests more realistic, since this policy only matters when inputfilter is
4334 * on.
4335 */
4336 mDispatcher->setInputFilterEnabled(true);
4337
4338 std::shared_ptr<InputApplicationHandle> application =
4339 std::make_shared<FakeApplicationHandle>();
4340 mWindow =
4341 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4342
4343 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4344 mWindow->setFocusable(true);
4345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4346 setFocusedWindow(mWindow);
4347 mWindow->consumeFocusEvent(true);
4348 }
4349
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004350 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4351 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004352 KeyEvent event;
4353
4354 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4355 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4356 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4357 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4358 const int32_t additionalPolicyFlags =
4359 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004361 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004362 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4363 policyFlags | additionalPolicyFlags));
4364
4365 InputEvent* received = mWindow->consume();
4366 ASSERT_NE(nullptr, received);
4367 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004368 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4369 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4370 ASSERT_EQ(flags, keyEvent.getFlags());
4371 }
4372
4373 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4374 int32_t flags) {
4375 MotionEvent event;
4376 PointerProperties pointerProperties[1];
4377 PointerCoords pointerCoords[1];
4378 pointerProperties[0].clear();
4379 pointerProperties[0].id = 0;
4380 pointerCoords[0].clear();
4381 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4382 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4383
4384 ui::Transform identityTransform;
4385 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4386 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4387 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4388 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4389 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004390 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004391 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004392 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4393
4394 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004396 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004397 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4398 policyFlags | additionalPolicyFlags));
4399
4400 InputEvent* received = mWindow->consume();
4401 ASSERT_NE(nullptr, received);
4402 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4403 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4404 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4405 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004406 }
4407
4408private:
4409 sp<FakeWindowHandle> mWindow;
4410};
4411
4412TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004413 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4414 // filter. Without it, the event will no different from a regularly injected event, and the
4415 // injected device id will be overwritten.
4416 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4417 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004418}
4419
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004420TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004421 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004422 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4423 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4424}
4425
4426TEST_F(InputFilterInjectionPolicyTest,
4427 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4428 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4429 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4430 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431}
4432
4433TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4434 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004435 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004436}
4437
chaviwfd6d3512019-03-25 13:23:49 -07004438class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004439 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004440 InputDispatcherTest::SetUp();
4441
Chris Yea209fde2020-07-22 13:54:51 -07004442 std::shared_ptr<FakeApplicationHandle> application =
4443 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004444 mUnfocusedWindow =
4445 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004446 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004447
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004448 mFocusedWindow =
4449 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4450 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004451
4452 // Set focused application.
4453 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004454 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004455
4456 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004458 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004459 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004460 }
4461
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004462 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004463 InputDispatcherTest::TearDown();
4464
4465 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004466 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004467 }
4468
4469protected:
4470 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004471 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004472 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004473};
4474
4475// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4476// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4477// the onPointerDownOutsideFocus callback.
4478TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004480 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4481 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004483 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004484
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004485 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004486 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4487}
4488
4489// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4490// DOWN on the window that doesn't have focus. Ensure no window received the
4491// onPointerDownOutsideFocus callback.
4492TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004496 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004497
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004498 ASSERT_TRUE(mDispatcher->waitForIdle());
4499 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004500}
4501
4502// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4503// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4504TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4506 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004508 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004509
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004510 ASSERT_TRUE(mDispatcher->waitForIdle());
4511 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004512}
4513
4514// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4515// DOWN on the window that already has focus. Ensure no window received the
4516// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004517TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004520 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004521 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004522 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004523
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004524 ASSERT_TRUE(mDispatcher->waitForIdle());
4525 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004526}
4527
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004528// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4529// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4530TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4531 const MotionEvent event =
4532 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4533 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4534 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4535 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4536 .build();
4537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4538 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4539 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4540
4541 ASSERT_TRUE(mDispatcher->waitForIdle());
4542 mFakePolicy->assertOnPointerDownWasNotCalled();
4543 // Ensure that the unfocused window did not receive any FOCUS events.
4544 mUnfocusedWindow->assertNoEvents();
4545}
4546
chaviwaf87b3e2019-10-01 16:59:28 -07004547// These tests ensures we can send touch events to a single client when there are multiple input
4548// windows that point to the same client token.
4549class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4550 virtual void SetUp() override {
4551 InputDispatcherTest::SetUp();
4552
Chris Yea209fde2020-07-22 13:54:51 -07004553 std::shared_ptr<FakeApplicationHandle> application =
4554 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004555 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4556 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004557 mWindow1->setFrame(Rect(0, 0, 100, 100));
4558
4559 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4560 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004561 mWindow2->setFrame(Rect(100, 100, 200, 200));
4562
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004564 }
4565
4566protected:
4567 sp<FakeWindowHandle> mWindow1;
4568 sp<FakeWindowHandle> mWindow2;
4569
4570 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004571 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004572 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4573 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004574 }
4575
4576 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4577 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004578 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004579 InputEvent* event = window->consume();
4580
4581 ASSERT_NE(nullptr, event) << name.c_str()
4582 << ": consumer should have returned non-NULL event.";
4583
4584 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4585 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4586 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4587
4588 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004589 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004590
4591 for (size_t i = 0; i < points.size(); i++) {
4592 float expectedX = points[i].x;
4593 float expectedY = points[i].y;
4594
4595 EXPECT_EQ(expectedX, motionEvent.getX(i))
4596 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4597 << ", got " << motionEvent.getX(i);
4598 EXPECT_EQ(expectedY, motionEvent.getY(i))
4599 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4600 << ", got " << motionEvent.getY(i);
4601 }
4602 }
chaviw9eaa22c2020-07-01 16:21:27 -07004603
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004604 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004605 std::vector<PointF> expectedPoints) {
4606 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4607 ADISPLAY_ID_DEFAULT, touchedPoints);
4608 mDispatcher->notifyMotion(&motionArgs);
4609
4610 // Always consume from window1 since it's the window that has the InputReceiver
4611 consumeMotionEvent(mWindow1, action, expectedPoints);
4612 }
chaviwaf87b3e2019-10-01 16:59:28 -07004613};
4614
4615TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4616 // Touch Window 1
4617 PointF touchedPoint = {10, 10};
4618 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004619 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004620
4621 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004622 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004623
4624 // Touch Window 2
4625 touchedPoint = {150, 150};
4626 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004627 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004628}
4629
chaviw9eaa22c2020-07-01 16:21:27 -07004630TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4631 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004632 mWindow2->setWindowScale(0.5f, 0.5f);
4633
4634 // Touch Window 1
4635 PointF touchedPoint = {10, 10};
4636 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004637 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004638 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004639 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004640
4641 // Touch Window 2
4642 touchedPoint = {150, 150};
4643 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004644 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4645 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004646
chaviw9eaa22c2020-07-01 16:21:27 -07004647 // Update the transform so rotation is set
4648 mWindow2->setWindowTransform(0, -1, 1, 0);
4649 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4650 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004651}
4652
chaviw9eaa22c2020-07-01 16:21:27 -07004653TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004654 mWindow2->setWindowScale(0.5f, 0.5f);
4655
4656 // Touch Window 1
4657 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4658 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004659 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004660
4661 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004662 touchedPoints.push_back(PointF{150, 150});
4663 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004664 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004665
chaviw9eaa22c2020-07-01 16:21:27 -07004666 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004667 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004668 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004669
chaviw9eaa22c2020-07-01 16:21:27 -07004670 // Update the transform so rotation is set for Window 2
4671 mWindow2->setWindowTransform(0, -1, 1, 0);
4672 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004673 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004674}
4675
chaviw9eaa22c2020-07-01 16:21:27 -07004676TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004677 mWindow2->setWindowScale(0.5f, 0.5f);
4678
4679 // Touch Window 1
4680 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4681 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004682 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004683
4684 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004685 touchedPoints.push_back(PointF{150, 150});
4686 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004687
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004688 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004689
4690 // Move both windows
4691 touchedPoints = {{20, 20}, {175, 175}};
4692 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4693 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4694
chaviw9eaa22c2020-07-01 16:21:27 -07004695 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004696
chaviw9eaa22c2020-07-01 16:21:27 -07004697 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004698 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004699 expectedPoints.pop_back();
4700
4701 // Touch Window 2
4702 mWindow2->setWindowTransform(0, -1, 1, 0);
4703 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004704 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004705
4706 // Move both windows
4707 touchedPoints = {{20, 20}, {175, 175}};
4708 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4709 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4710
4711 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004712}
4713
4714TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4715 mWindow1->setWindowScale(0.5f, 0.5f);
4716
4717 // Touch Window 1
4718 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4719 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004720 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004721
4722 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004723 touchedPoints.push_back(PointF{150, 150});
4724 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004725
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004726 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004727
4728 // Move both windows
4729 touchedPoints = {{20, 20}, {175, 175}};
4730 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4731 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4732
chaviw9eaa22c2020-07-01 16:21:27 -07004733 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004734}
4735
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004736class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4737 virtual void SetUp() override {
4738 InputDispatcherTest::SetUp();
4739
Chris Yea209fde2020-07-22 13:54:51 -07004740 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004741 mApplication->setDispatchingTimeout(20ms);
4742 mWindow =
4743 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4744 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004745 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004746 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004747
4748 // Set focused application.
4749 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4750
4751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004752 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004753 mWindow->consumeFocusEvent(true);
4754 }
4755
4756 virtual void TearDown() override {
4757 InputDispatcherTest::TearDown();
4758 mWindow.clear();
4759 }
4760
4761protected:
Chris Yea209fde2020-07-22 13:54:51 -07004762 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004763 sp<FakeWindowHandle> mWindow;
4764 static constexpr PointF WINDOW_LOCATION = {20, 20};
4765
4766 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004768 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4769 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004770 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004771 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4772 WINDOW_LOCATION));
4773 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004774
4775 sp<FakeWindowHandle> addSpyWindow() {
4776 sp<FakeWindowHandle> spy =
4777 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4778 spy->setTrustedOverlay(true);
4779 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004780 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004781 spy->setDispatchingTimeout(30ms);
4782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4783 return spy;
4784 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004785};
4786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004787// Send a tap and respond, which should not cause an ANR.
4788TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4789 tapOnWindow();
4790 mWindow->consumeMotionDown();
4791 mWindow->consumeMotionUp();
4792 ASSERT_TRUE(mDispatcher->waitForIdle());
4793 mFakePolicy->assertNotifyAnrWasNotCalled();
4794}
4795
4796// Send a regular key and respond, which should not cause an ANR.
4797TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4800 ASSERT_TRUE(mDispatcher->waitForIdle());
4801 mFakePolicy->assertNotifyAnrWasNotCalled();
4802}
4803
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004804TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4805 mWindow->setFocusable(false);
4806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4807 mWindow->consumeFocusEvent(false);
4808
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004810 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004811 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4812 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004814 // Key will not go to window because we have no focused window.
4815 // The 'no focused window' ANR timer should start instead.
4816
4817 // Now, the focused application goes away.
4818 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4819 // The key should get dropped and there should be no ANR.
4820
4821 ASSERT_TRUE(mDispatcher->waitForIdle());
4822 mFakePolicy->assertNotifyAnrWasNotCalled();
4823}
4824
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004825// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4827// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004828TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004830 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4831 WINDOW_LOCATION));
4832
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004833 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4834 ASSERT_TRUE(sequenceNum);
4835 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004836 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 mWindow->finishEvent(*sequenceNum);
4839 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4840 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004841 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004842 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004843}
4844
4845// Send a key to the app and have the app not respond right away.
4846TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4847 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004849 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4850 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004851 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004852 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004853 ASSERT_TRUE(mDispatcher->waitForIdle());
4854}
4855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856// We have a focused application, but no focused window
4857TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004858 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4860 mWindow->consumeFocusEvent(false);
4861
4862 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4865 WINDOW_LOCATION));
4866 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4867 mDispatcher->waitForIdle();
4868 mFakePolicy->assertNotifyAnrWasNotCalled();
4869
4870 // Once a focused event arrives, we get an ANR for this application
4871 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4872 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004873 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004875 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004876 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004878 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 ASSERT_TRUE(mDispatcher->waitForIdle());
4880}
4881
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004882/**
4883 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4884 * there will not be an ANR.
4885 */
4886TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4887 mWindow->setFocusable(false);
4888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4889 mWindow->consumeFocusEvent(false);
4890
4891 KeyEvent event;
4892 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4893 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4894
4895 // Define a valid key down event that is stale (too old).
4896 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4897 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4898 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4899
4900 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4901
4902 InputEventInjectionResult result =
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004903 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004904 InputEventInjectionSync::WAIT_FOR_RESULT,
4905 INJECT_EVENT_TIMEOUT, policyFlags);
4906 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4907 << "Injection should fail because the event is stale";
4908
4909 ASSERT_TRUE(mDispatcher->waitForIdle());
4910 mFakePolicy->assertNotifyAnrWasNotCalled();
4911 mWindow->assertNoEvents();
4912}
4913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004915// Make sure that we don't notify policy twice about the same ANR.
4916TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004917 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4919 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 // Once a focused event arrives, we get an ANR for this application
4922 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4923 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004924 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004926 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004927 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004928 const std::chrono::duration appTimeout =
4929 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004930 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004931
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004932 std::this_thread::sleep_for(appTimeout);
4933 // ANR should not be raised again. It is up to policy to do that if it desires.
4934 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004936 // If we now get a focused window, the ANR should stop, but the policy handles that via
4937 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004938 ASSERT_TRUE(mDispatcher->waitForIdle());
4939}
4940
4941// We have a focused application, but no focused window
4942TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004943 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004944 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4945 mWindow->consumeFocusEvent(false);
4946
4947 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004948 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004949 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004950 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4951 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004952
4953 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
4956 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004957 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958 ASSERT_TRUE(mDispatcher->waitForIdle());
4959 mWindow->assertNoEvents();
4960}
4961
4962/**
4963 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4964 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4965 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4966 * the ANR mechanism should still work.
4967 *
4968 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4969 * DOWN event, while not responding on the second one.
4970 */
4971TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4972 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4973 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4974 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4975 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4976 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004977 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004978
4979 // Now send ACTION_UP, with identical timestamp
4980 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4981 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4982 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4983 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004984 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985
4986 // We have now sent down and up. Let's consume first event and then ANR on the second.
4987 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4988 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004989 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004990}
4991
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004992// A spy window can receive an ANR
4993TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4994 sp<FakeWindowHandle> spy = addSpyWindow();
4995
4996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4998 WINDOW_LOCATION));
4999 mWindow->consumeMotionDown();
5000
5001 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
5002 ASSERT_TRUE(sequenceNum);
5003 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005004 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005005
5006 spy->finishEvent(*sequenceNum);
5007 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
5008 0 /*flags*/);
5009 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005010 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005011}
5012
5013// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005015TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
5016 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005017
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5019 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005022
5023 // Stuck on the ACTION_UP
5024 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005025 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005026
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005027 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005029 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5030 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031
5032 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5033 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005034 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005035 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005036 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037}
5038
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005039// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005040// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005041TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
5042 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005043
5044 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005045 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5046 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047
5048 mWindow->consumeMotionDown();
5049 // Stuck on the ACTION_UP
5050 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005051 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005052
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005053 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005055 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5056 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005057
5058 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
5059 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005060 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005061 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005062 spy->assertNoEvents();
5063}
5064
5065TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
5066 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
5067
5068 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
5069
5070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5071 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5072 WINDOW_LOCATION));
5073
5074 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5075 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
5076 ASSERT_TRUE(consumeSeq);
5077
Prabir Pradhanedd96402022-02-15 01:46:16 -08005078 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08005079
5080 monitor.finishEvent(*consumeSeq);
5081 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
5082
5083 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005084 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085}
5086
5087// If a window is unresponsive, then you get anr. if the window later catches up and starts to
5088// process events, you don't get an anr. When the window later becomes unresponsive again, you
5089// get an ANR again.
5090// 1. tap -> block on ACTION_UP -> receive ANR
5091// 2. consume all pending events (= queue becomes healthy again)
5092// 3. tap again -> block on ACTION_UP again -> receive ANR second time
5093TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
5094 tapOnWindow();
5095
5096 mWindow->consumeMotionDown();
5097 // Block on ACTION_UP
5098 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005099 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5101 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005102 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005103 mWindow->assertNoEvents();
5104
5105 tapOnWindow();
5106 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005107 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005108 mWindow->consumeMotionUp();
5109
5110 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005111 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005112 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113 mWindow->assertNoEvents();
5114}
5115
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005116// If a connection remains unresponsive for a while, make sure policy is only notified once about
5117// it.
5118TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005120 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5121 WINDOW_LOCATION));
5122
5123 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005124 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005125 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005126 // 'notifyConnectionUnresponsive' should only be called once per connection
5127 mFakePolicy->assertNotifyAnrWasNotCalled();
5128 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005129 mWindow->consumeMotionDown();
5130 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5131 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5132 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005133 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005134 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005135 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136}
5137
5138/**
5139 * If a window is processing a motion event, and then a key event comes in, the key event should
5140 * not to to the focused window until the motion is processed.
5141 *
5142 * Warning!!!
5143 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5144 * and the injection timeout that we specify when injecting the key.
5145 * We must have the injection timeout (10ms) be smaller than
5146 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5147 *
5148 * If that value changes, this test should also change.
5149 */
5150TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5151 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5153
5154 tapOnWindow();
5155 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5156 ASSERT_TRUE(downSequenceNum);
5157 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5158 ASSERT_TRUE(upSequenceNum);
5159 // Don't finish the events yet, and send a key
5160 // Injection will "succeed" because we will eventually give up and send the key to the focused
5161 // window even if motions are still being processed. But because the injection timeout is short,
5162 // we will receive INJECTION_TIMED_OUT as the result.
5163
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005164 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005166 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5167 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005168 // Key will not be sent to the window, yet, because the window is still processing events
5169 // and the key remains pending, waiting for the touch events to be processed
5170 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5171 ASSERT_FALSE(keySequenceNum);
5172
5173 std::this_thread::sleep_for(500ms);
5174 // if we wait long enough though, dispatcher will give up, and still send the key
5175 // to the focused window, even though we have not yet finished the motion event
5176 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5177 mWindow->finishEvent(*downSequenceNum);
5178 mWindow->finishEvent(*upSequenceNum);
5179}
5180
5181/**
5182 * If a window is processing a motion event, and then a key event comes in, the key event should
5183 * not go to the focused window until the motion is processed.
5184 * If then a new motion comes in, then the pending key event should be going to the currently
5185 * focused window right away.
5186 */
5187TEST_F(InputDispatcherSingleWindowAnr,
5188 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5189 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5191
5192 tapOnWindow();
5193 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5194 ASSERT_TRUE(downSequenceNum);
5195 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5196 ASSERT_TRUE(upSequenceNum);
5197 // Don't finish the events yet, and send a key
5198 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005200 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005201 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 // At this point, key is still pending, and should not be sent to the application yet.
5203 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5204 ASSERT_FALSE(keySequenceNum);
5205
5206 // Now tap down again. It should cause the pending key to go to the focused window right away.
5207 tapOnWindow();
5208 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5209 // the other events yet. We can finish events in any order.
5210 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5211 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5212 mWindow->consumeMotionDown();
5213 mWindow->consumeMotionUp();
5214 mWindow->assertNoEvents();
5215}
5216
5217class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5218 virtual void SetUp() override {
5219 InputDispatcherTest::SetUp();
5220
Chris Yea209fde2020-07-22 13:54:51 -07005221 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222 mApplication->setDispatchingTimeout(10ms);
5223 mUnfocusedWindow =
5224 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5225 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005226 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005227 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005228
5229 mFocusedWindow =
5230 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005231 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005232 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005233
5234 // Set focused application.
5235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005236 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237
5238 // Expect one focus window exist in display.
5239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005240 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241 mFocusedWindow->consumeFocusEvent(true);
5242 }
5243
5244 virtual void TearDown() override {
5245 InputDispatcherTest::TearDown();
5246
5247 mUnfocusedWindow.clear();
5248 mFocusedWindow.clear();
5249 }
5250
5251protected:
Chris Yea209fde2020-07-22 13:54:51 -07005252 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005253 sp<FakeWindowHandle> mUnfocusedWindow;
5254 sp<FakeWindowHandle> mFocusedWindow;
5255 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5256 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5257 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5258
5259 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5260
5261 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5262
5263private:
5264 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005266 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5267 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005269 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5270 location));
5271 }
5272};
5273
5274// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5275// should be ANR'd first.
5276TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005278 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5279 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005280 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005281 mFocusedWindow->consumeMotionDown();
5282 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5283 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5284 // We consumed all events, so no ANR
5285 ASSERT_TRUE(mDispatcher->waitForIdle());
5286 mFakePolicy->assertNotifyAnrWasNotCalled();
5287
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005289 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5290 FOCUSED_WINDOW_LOCATION));
5291 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5292 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005293
5294 const std::chrono::duration timeout =
5295 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005296 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005297 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5298 // sequence to make it consistent
5299 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005300 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005301 mFocusedWindow->consumeMotionDown();
5302 // This cancel is generated because the connection was unresponsive
5303 mFocusedWindow->consumeMotionCancel();
5304 mFocusedWindow->assertNoEvents();
5305 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005306 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005307 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5308 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005309 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005310}
5311
5312// If we have 2 windows with identical timeouts that are both unresponsive,
5313// it doesn't matter which order they should have ANR.
5314// But we should receive ANR for both.
5315TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5316 // Set the timeout for unfocused window to match the focused window
5317 mUnfocusedWindow->setDispatchingTimeout(10ms);
5318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5319
5320 tapOnFocusedWindow();
5321 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005322 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5323 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5324 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005325
5326 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005327 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5328 mFocusedWindow->getToken() == anrConnectionToken2);
5329 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5330 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005331
5332 ASSERT_TRUE(mDispatcher->waitForIdle());
5333 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005334
5335 mFocusedWindow->consumeMotionDown();
5336 mFocusedWindow->consumeMotionUp();
5337 mUnfocusedWindow->consumeMotionOutside();
5338
Prabir Pradhanedd96402022-02-15 01:46:16 -08005339 sp<IBinder> responsiveToken1, responsiveToken2;
5340 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5341 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005342
5343 // Both applications should be marked as responsive, in any order
5344 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5345 mFocusedWindow->getToken() == responsiveToken2);
5346 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5347 mUnfocusedWindow->getToken() == responsiveToken2);
5348 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005349}
5350
5351// If a window is already not responding, the second tap on the same window should be ignored.
5352// We should also log an error to account for the dropped event (not tested here).
5353// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5354TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5355 tapOnFocusedWindow();
5356 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5357 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5358 // Receive the events, but don't respond
5359 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5360 ASSERT_TRUE(downEventSequenceNum);
5361 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5362 ASSERT_TRUE(upEventSequenceNum);
5363 const std::chrono::duration timeout =
5364 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005365 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005366
5367 // Tap once again
5368 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005369 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005370 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5371 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005372 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005373 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5374 FOCUSED_WINDOW_LOCATION));
5375 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5376 // valid touch target
5377 mUnfocusedWindow->assertNoEvents();
5378
5379 // Consume the first tap
5380 mFocusedWindow->finishEvent(*downEventSequenceNum);
5381 mFocusedWindow->finishEvent(*upEventSequenceNum);
5382 ASSERT_TRUE(mDispatcher->waitForIdle());
5383 // The second tap did not go to the focused window
5384 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005385 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005386 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5387 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005388 mFakePolicy->assertNotifyAnrWasNotCalled();
5389}
5390
5391// If you tap outside of all windows, there will not be ANR
5392TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005393 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005394 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5395 LOCATION_OUTSIDE_ALL_WINDOWS));
5396 ASSERT_TRUE(mDispatcher->waitForIdle());
5397 mFakePolicy->assertNotifyAnrWasNotCalled();
5398}
5399
5400// Since the focused window is paused, tapping on it should not produce any events
5401TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5402 mFocusedWindow->setPaused(true);
5403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5404
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005405 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005406 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5407 FOCUSED_WINDOW_LOCATION));
5408
5409 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5410 ASSERT_TRUE(mDispatcher->waitForIdle());
5411 // Should not ANR because the window is paused, and touches shouldn't go to it
5412 mFakePolicy->assertNotifyAnrWasNotCalled();
5413
5414 mFocusedWindow->assertNoEvents();
5415 mUnfocusedWindow->assertNoEvents();
5416}
5417
5418/**
5419 * If a window is processing a motion event, and then a key event comes in, the key event should
5420 * not to to the focused window until the motion is processed.
5421 * If a different window becomes focused at this time, the key should go to that window instead.
5422 *
5423 * Warning!!!
5424 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5425 * and the injection timeout that we specify when injecting the key.
5426 * We must have the injection timeout (10ms) be smaller than
5427 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5428 *
5429 * If that value changes, this test should also change.
5430 */
5431TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5432 // Set a long ANR timeout to prevent it from triggering
5433 mFocusedWindow->setDispatchingTimeout(2s);
5434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5435
5436 tapOnUnfocusedWindow();
5437 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5438 ASSERT_TRUE(downSequenceNum);
5439 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5440 ASSERT_TRUE(upSequenceNum);
5441 // Don't finish the events yet, and send a key
5442 // Injection will succeed because we will eventually give up and send the key to the focused
5443 // window even if motions are still being processed.
5444
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005445 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005446 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005447 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005449 // Key will not be sent to the window, yet, because the window is still processing events
5450 // and the key remains pending, waiting for the touch events to be processed
5451 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5452 ASSERT_FALSE(keySequenceNum);
5453
5454 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005455 mFocusedWindow->setFocusable(false);
5456 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005458 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005459
5460 // Focus events should precede the key events
5461 mUnfocusedWindow->consumeFocusEvent(true);
5462 mFocusedWindow->consumeFocusEvent(false);
5463
5464 // Finish the tap events, which should unblock dispatcher
5465 mUnfocusedWindow->finishEvent(*downSequenceNum);
5466 mUnfocusedWindow->finishEvent(*upSequenceNum);
5467
5468 // Now that all queues are cleared and no backlog in the connections, the key event
5469 // can finally go to the newly focused "mUnfocusedWindow".
5470 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5471 mFocusedWindow->assertNoEvents();
5472 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005473 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005474}
5475
5476// When the touch stream is split across 2 windows, and one of them does not respond,
5477// then ANR should be raised and the touch should be canceled for the unresponsive window.
5478// The other window should not be affected by that.
5479TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5480 // Touch Window 1
5481 NotifyMotionArgs motionArgs =
5482 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5483 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5484 mDispatcher->notifyMotion(&motionArgs);
5485 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5486 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5487
5488 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005489 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5490 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005491 mDispatcher->notifyMotion(&motionArgs);
5492
5493 const std::chrono::duration timeout =
5494 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005495 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005496
5497 mUnfocusedWindow->consumeMotionDown();
5498 mFocusedWindow->consumeMotionDown();
5499 // Focused window may or may not receive ACTION_MOVE
5500 // But it should definitely receive ACTION_CANCEL due to the ANR
5501 InputEvent* event;
5502 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5503 ASSERT_TRUE(moveOrCancelSequenceNum);
5504 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5505 ASSERT_NE(nullptr, event);
5506 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5507 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5508 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5509 mFocusedWindow->consumeMotionCancel();
5510 } else {
5511 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5512 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005513 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005514 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5515 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005517 mUnfocusedWindow->assertNoEvents();
5518 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005519 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005520}
5521
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005522/**
5523 * If we have no focused window, and a key comes in, we start the ANR timer.
5524 * The focused application should add a focused window before the timer runs out to prevent ANR.
5525 *
5526 * If the user touches another application during this time, the key should be dropped.
5527 * Next, if a new focused window comes in, without toggling the focused application,
5528 * then no ANR should occur.
5529 *
5530 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5531 * but in some cases the policy may not update the focused application.
5532 */
5533TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5534 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5535 std::make_shared<FakeApplicationHandle>();
5536 focusedApplication->setDispatchingTimeout(60ms);
5537 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5538 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5539 mFocusedWindow->setFocusable(false);
5540
5541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5542 mFocusedWindow->consumeFocusEvent(false);
5543
5544 // Send a key. The ANR timer should start because there is no focused window.
5545 // 'focusedApplication' will get blamed if this timer completes.
5546 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005547 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005548 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005549 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5550 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005552
5553 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5554 // then the injected touches won't cause the focused event to get dropped.
5555 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5556 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5557 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5558 // For this test, it means that the key would get delivered to the window once it becomes
5559 // focused.
5560 std::this_thread::sleep_for(10ms);
5561
5562 // Touch unfocused window. This should force the pending key to get dropped.
5563 NotifyMotionArgs motionArgs =
5564 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5565 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5566 mDispatcher->notifyMotion(&motionArgs);
5567
5568 // We do not consume the motion right away, because that would require dispatcher to first
5569 // process (== drop) the key event, and by that time, ANR will be raised.
5570 // Set the focused window first.
5571 mFocusedWindow->setFocusable(true);
5572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5573 setFocusedWindow(mFocusedWindow);
5574 mFocusedWindow->consumeFocusEvent(true);
5575 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5576 // to another application. This could be a bug / behaviour in the policy.
5577
5578 mUnfocusedWindow->consumeMotionDown();
5579
5580 ASSERT_TRUE(mDispatcher->waitForIdle());
5581 // Should not ANR because we actually have a focused window. It was just added too slowly.
5582 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5583}
5584
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005585// These tests ensure we cannot send touch events to a window that's positioned behind a window
5586// that has feature NO_INPUT_CHANNEL.
5587// Layout:
5588// Top (closest to user)
5589// mNoInputWindow (above all windows)
5590// mBottomWindow
5591// Bottom (furthest from user)
5592class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5593 virtual void SetUp() override {
5594 InputDispatcherTest::SetUp();
5595
5596 mApplication = std::make_shared<FakeApplicationHandle>();
5597 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5598 "Window without input channel", ADISPLAY_ID_DEFAULT,
5599 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5600
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005601 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005602 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5603 // It's perfectly valid for this window to not have an associated input channel
5604
5605 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5606 ADISPLAY_ID_DEFAULT);
5607 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5608
5609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5610 }
5611
5612protected:
5613 std::shared_ptr<FakeApplicationHandle> mApplication;
5614 sp<FakeWindowHandle> mNoInputWindow;
5615 sp<FakeWindowHandle> mBottomWindow;
5616};
5617
5618TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5619 PointF touchedPoint = {10, 10};
5620
5621 NotifyMotionArgs motionArgs =
5622 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5623 ADISPLAY_ID_DEFAULT, {touchedPoint});
5624 mDispatcher->notifyMotion(&motionArgs);
5625
5626 mNoInputWindow->assertNoEvents();
5627 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5628 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5629 // and therefore should prevent mBottomWindow from receiving touches
5630 mBottomWindow->assertNoEvents();
5631}
5632
5633/**
5634 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5635 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5636 */
5637TEST_F(InputDispatcherMultiWindowOcclusionTests,
5638 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5639 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5640 "Window with input channel and NO_INPUT_CHANNEL",
5641 ADISPLAY_ID_DEFAULT);
5642
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005643 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005644 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5646
5647 PointF touchedPoint = {10, 10};
5648
5649 NotifyMotionArgs motionArgs =
5650 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5651 ADISPLAY_ID_DEFAULT, {touchedPoint});
5652 mDispatcher->notifyMotion(&motionArgs);
5653
5654 mNoInputWindow->assertNoEvents();
5655 mBottomWindow->assertNoEvents();
5656}
5657
Vishnu Nair958da932020-08-21 17:12:37 -07005658class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5659protected:
5660 std::shared_ptr<FakeApplicationHandle> mApp;
5661 sp<FakeWindowHandle> mWindow;
5662 sp<FakeWindowHandle> mMirror;
5663
5664 virtual void SetUp() override {
5665 InputDispatcherTest::SetUp();
5666 mApp = std::make_shared<FakeApplicationHandle>();
5667 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5668 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5669 mWindow->getToken());
5670 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5671 mWindow->setFocusable(true);
5672 mMirror->setFocusable(true);
5673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5674 }
5675};
5676
5677TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5678 // Request focus on a mirrored window
5679 setFocusedWindow(mMirror);
5680
5681 // window gets focused
5682 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5684 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005685 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5686}
5687
5688// A focused & mirrored window remains focused only if the window and its mirror are both
5689// focusable.
5690TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5691 setFocusedWindow(mMirror);
5692
5693 // window gets focused
5694 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5696 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005697 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5699 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005700 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5701
5702 mMirror->setFocusable(false);
5703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5704
5705 // window loses focus since one of the windows associated with the token in not focusable
5706 mWindow->consumeFocusEvent(false);
5707
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005708 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5709 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005710 mWindow->assertNoEvents();
5711}
5712
5713// A focused & mirrored window remains focused until the window and its mirror both become
5714// invisible.
5715TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5716 setFocusedWindow(mMirror);
5717
5718 // window gets focused
5719 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005720 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5721 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005722 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5724 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005725 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5726
5727 mMirror->setVisible(false);
5728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5729
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5731 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005732 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5734 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005735 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5736
5737 mWindow->setVisible(false);
5738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5739
5740 // window loses focus only after all windows associated with the token become invisible.
5741 mWindow->consumeFocusEvent(false);
5742
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005743 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5744 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005745 mWindow->assertNoEvents();
5746}
5747
5748// A focused & mirrored window remains focused until both windows are removed.
5749TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5750 setFocusedWindow(mMirror);
5751
5752 // window gets focused
5753 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5755 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005756 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5758 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005759 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5760
5761 // single window is removed but the window token remains focused
5762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5763
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5765 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005766 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5768 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005769 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5770
5771 // Both windows are removed
5772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5773 mWindow->consumeFocusEvent(false);
5774
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005775 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5776 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005777 mWindow->assertNoEvents();
5778}
5779
5780// Focus request can be pending until one window becomes visible.
5781TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5782 // Request focus on an invisible mirror.
5783 mWindow->setVisible(false);
5784 mMirror->setVisible(false);
5785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5786 setFocusedWindow(mMirror);
5787
5788 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005790 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005791 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005792
5793 mMirror->setVisible(true);
5794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5795
5796 // window gets focused
5797 mWindow->consumeFocusEvent(true);
5798 // window gets the pending key event
5799 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5800}
Prabir Pradhan99987712020-11-10 18:43:05 -08005801
5802class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5803protected:
5804 std::shared_ptr<FakeApplicationHandle> mApp;
5805 sp<FakeWindowHandle> mWindow;
5806 sp<FakeWindowHandle> mSecondWindow;
5807
5808 void SetUp() override {
5809 InputDispatcherTest::SetUp();
5810 mApp = std::make_shared<FakeApplicationHandle>();
5811 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5812 mWindow->setFocusable(true);
5813 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5814 mSecondWindow->setFocusable(true);
5815
5816 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5818
5819 setFocusedWindow(mWindow);
5820 mWindow->consumeFocusEvent(true);
5821 }
5822
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005823 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5824 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005825 mDispatcher->notifyPointerCaptureChanged(&args);
5826 }
5827
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005828 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5829 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005830 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005831 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5832 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005833 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005834 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005835 }
5836};
5837
5838TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5839 // Ensure that capture cannot be obtained for unfocused windows.
5840 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5841 mFakePolicy->assertSetPointerCaptureNotCalled();
5842 mSecondWindow->assertNoEvents();
5843
5844 // Ensure that capture can be enabled from the focus window.
5845 requestAndVerifyPointerCapture(mWindow, true);
5846
5847 // Ensure that capture cannot be disabled from a window that does not have capture.
5848 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5849 mFakePolicy->assertSetPointerCaptureNotCalled();
5850
5851 // Ensure that capture can be disabled from the window with capture.
5852 requestAndVerifyPointerCapture(mWindow, false);
5853}
5854
5855TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005856 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005857
5858 setFocusedWindow(mSecondWindow);
5859
5860 // Ensure that the capture disabled event was sent first.
5861 mWindow->consumeCaptureEvent(false);
5862 mWindow->consumeFocusEvent(false);
5863 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005864 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005865
5866 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005867 notifyPointerCaptureChanged({});
5868 notifyPointerCaptureChanged(request);
5869 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005870 mWindow->assertNoEvents();
5871 mSecondWindow->assertNoEvents();
5872 mFakePolicy->assertSetPointerCaptureNotCalled();
5873}
5874
5875TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005876 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005877
5878 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005879 notifyPointerCaptureChanged({});
5880 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005881
5882 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005883 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005884 mWindow->consumeCaptureEvent(false);
5885 mWindow->assertNoEvents();
5886}
5887
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005888TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5889 requestAndVerifyPointerCapture(mWindow, true);
5890
5891 // The first window loses focus.
5892 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005893 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005894 mWindow->consumeCaptureEvent(false);
5895
5896 // Request Pointer Capture from the second window before the notification from InputReader
5897 // arrives.
5898 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005899 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005900
5901 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005902 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005903
5904 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005905 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005906
5907 mSecondWindow->consumeFocusEvent(true);
5908 mSecondWindow->consumeCaptureEvent(true);
5909}
5910
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005911TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5912 // App repeatedly enables and disables capture.
5913 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5914 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5915 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5916 mFakePolicy->assertSetPointerCaptureCalled(false);
5917 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5918 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5919
5920 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5921 // first request is now stale, this should do nothing.
5922 notifyPointerCaptureChanged(firstRequest);
5923 mWindow->assertNoEvents();
5924
5925 // InputReader notifies that the second request was enabled.
5926 notifyPointerCaptureChanged(secondRequest);
5927 mWindow->consumeCaptureEvent(true);
5928}
5929
Prabir Pradhan7092e262022-05-03 16:51:09 +00005930TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5931 requestAndVerifyPointerCapture(mWindow, true);
5932
5933 // App toggles pointer capture off and on.
5934 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5935 mFakePolicy->assertSetPointerCaptureCalled(false);
5936
5937 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5938 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5939
5940 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5941 // preceding "disable" request.
5942 notifyPointerCaptureChanged(enableRequest);
5943
5944 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5945 // any notifications.
5946 mWindow->assertNoEvents();
5947}
5948
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005949class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5950protected:
5951 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005952
5953 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5954 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5955
5956 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5957 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5958
5959 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5960 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5961 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5962 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5963 MAXIMUM_OBSCURING_OPACITY);
5964
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005965 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005966 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005967 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005968
5969 sp<FakeWindowHandle> mTouchWindow;
5970
5971 virtual void SetUp() override {
5972 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005973 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005974 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5975 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5976 }
5977
5978 virtual void TearDown() override {
5979 InputDispatcherTest::TearDown();
5980 mTouchWindow.clear();
5981 }
5982
chaviw3277faf2021-05-19 16:45:23 -05005983 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5984 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005985 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005986 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005987 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005988 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005989 return window;
5990 }
5991
5992 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5993 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5994 sp<FakeWindowHandle> window =
5995 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5996 // Generate an arbitrary PID based on the UID
5997 window->setOwnerInfo(1777 + (uid % 10000), uid);
5998 return window;
5999 }
6000
6001 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
6002 NotifyMotionArgs args =
6003 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6004 ADISPLAY_ID_DEFAULT, points);
6005 mDispatcher->notifyMotion(&args);
6006 }
6007};
6008
6009TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006010 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006011 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006013
6014 touch();
6015
6016 mTouchWindow->assertNoEvents();
6017}
6018
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006019TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00006020 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
6021 const sp<FakeWindowHandle>& w =
6022 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
6023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6024
6025 touch();
6026
6027 mTouchWindow->assertNoEvents();
6028}
6029
6030TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006031 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
6032 const sp<FakeWindowHandle>& w =
6033 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6034 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6035
6036 touch();
6037
6038 w->assertNoEvents();
6039}
6040
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006041TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006042 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
6043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006044
6045 touch();
6046
6047 mTouchWindow->consumeAnyMotionDown();
6048}
6049
6050TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006051 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006052 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006053 w->setFrame(Rect(0, 0, 50, 50));
6054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006055
6056 touch({PointF{100, 100}});
6057
6058 mTouchWindow->consumeAnyMotionDown();
6059}
6060
6061TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006062 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006063 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006064 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6065
6066 touch();
6067
6068 mTouchWindow->consumeAnyMotionDown();
6069}
6070
6071TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
6072 const sp<FakeWindowHandle>& w =
6073 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006075
6076 touch();
6077
6078 mTouchWindow->consumeAnyMotionDown();
6079}
6080
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006081TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
6082 const sp<FakeWindowHandle>& w =
6083 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
6084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6085
6086 touch();
6087
6088 w->assertNoEvents();
6089}
6090
6091/**
6092 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
6093 * inside) while letting them pass-through. Note that even though touch passes through the occluding
6094 * window, the occluding window will still receive ACTION_OUTSIDE event.
6095 */
6096TEST_F(InputDispatcherUntrustedTouchesTest,
6097 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
6098 const sp<FakeWindowHandle>& w =
6099 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006100 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006101 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6102
6103 touch();
6104
6105 w->consumeMotionOutside();
6106}
6107
6108TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6109 const sp<FakeWindowHandle>& w =
6110 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006111 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6113
6114 touch();
6115
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006116 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006117}
6118
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006119TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006120 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006121 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6122 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6124
6125 touch();
6126
6127 mTouchWindow->consumeAnyMotionDown();
6128}
6129
6130TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6131 const sp<FakeWindowHandle>& w =
6132 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6133 MAXIMUM_OBSCURING_OPACITY);
6134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006135
6136 touch();
6137
6138 mTouchWindow->consumeAnyMotionDown();
6139}
6140
6141TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006142 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006143 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6144 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6146
6147 touch();
6148
6149 mTouchWindow->assertNoEvents();
6150}
6151
6152TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6153 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6154 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006155 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6156 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006157 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006158 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6159 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006160 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6161
6162 touch();
6163
6164 mTouchWindow->assertNoEvents();
6165}
6166
6167TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6168 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6169 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006170 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6171 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006172 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006173 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6174 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6176
6177 touch();
6178
6179 mTouchWindow->consumeAnyMotionDown();
6180}
6181
6182TEST_F(InputDispatcherUntrustedTouchesTest,
6183 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6184 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006185 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6186 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006187 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006188 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6189 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6191
6192 touch();
6193
6194 mTouchWindow->consumeAnyMotionDown();
6195}
6196
6197TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6198 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006199 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6200 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006201 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006202 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6203 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006205
6206 touch();
6207
6208 mTouchWindow->assertNoEvents();
6209}
6210
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006211TEST_F(InputDispatcherUntrustedTouchesTest,
6212 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6213 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006214 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6215 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006216 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006217 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6218 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6220
6221 touch();
6222
6223 mTouchWindow->assertNoEvents();
6224}
6225
6226TEST_F(InputDispatcherUntrustedTouchesTest,
6227 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6228 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006229 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6230 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006231 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006232 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6233 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6235
6236 touch();
6237
6238 mTouchWindow->consumeAnyMotionDown();
6239}
6240
6241TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6242 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006243 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6244 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6246
6247 touch();
6248
6249 mTouchWindow->consumeAnyMotionDown();
6250}
6251
6252TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6253 const sp<FakeWindowHandle>& w =
6254 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6256
6257 touch();
6258
6259 mTouchWindow->consumeAnyMotionDown();
6260}
6261
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006262TEST_F(InputDispatcherUntrustedTouchesTest,
6263 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6264 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6265 const sp<FakeWindowHandle>& w =
6266 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6268
6269 touch();
6270
6271 mTouchWindow->assertNoEvents();
6272}
6273
6274TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6275 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6276 const sp<FakeWindowHandle>& w =
6277 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6279
6280 touch();
6281
6282 mTouchWindow->consumeAnyMotionDown();
6283}
6284
6285TEST_F(InputDispatcherUntrustedTouchesTest,
6286 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6287 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6288 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006289 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6290 OPACITY_ABOVE_THRESHOLD);
6291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6292
6293 touch();
6294
6295 mTouchWindow->consumeAnyMotionDown();
6296}
6297
6298TEST_F(InputDispatcherUntrustedTouchesTest,
6299 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6300 const sp<FakeWindowHandle>& w1 =
6301 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6302 OPACITY_BELOW_THRESHOLD);
6303 const sp<FakeWindowHandle>& w2 =
6304 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6305 OPACITY_BELOW_THRESHOLD);
6306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6307
6308 touch();
6309
6310 mTouchWindow->assertNoEvents();
6311}
6312
6313/**
6314 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6315 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6316 * (which alone would result in allowing touches) does not affect the blocking behavior.
6317 */
6318TEST_F(InputDispatcherUntrustedTouchesTest,
6319 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6320 const sp<FakeWindowHandle>& wB =
6321 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6322 OPACITY_BELOW_THRESHOLD);
6323 const sp<FakeWindowHandle>& wC =
6324 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6325 OPACITY_BELOW_THRESHOLD);
6326 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6327
6328 touch();
6329
6330 mTouchWindow->assertNoEvents();
6331}
6332
6333/**
6334 * This test is testing that a window from a different UID but with same application token doesn't
6335 * block the touch. Apps can share the application token for close UI collaboration for example.
6336 */
6337TEST_F(InputDispatcherUntrustedTouchesTest,
6338 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6339 const sp<FakeWindowHandle>& w =
6340 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6341 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6343
6344 touch();
6345
6346 mTouchWindow->consumeAnyMotionDown();
6347}
6348
arthurhungb89ccb02020-12-30 16:19:01 +08006349class InputDispatcherDragTests : public InputDispatcherTest {
6350protected:
6351 std::shared_ptr<FakeApplicationHandle> mApp;
6352 sp<FakeWindowHandle> mWindow;
6353 sp<FakeWindowHandle> mSecondWindow;
6354 sp<FakeWindowHandle> mDragWindow;
Arthur Hung02701602022-07-15 09:35:36 +00006355 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6356 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006357
6358 void SetUp() override {
6359 InputDispatcherTest::SetUp();
6360 mApp = std::make_shared<FakeApplicationHandle>();
6361 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6362 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006363
6364 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6365 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006366
6367 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6369 }
6370
Arthur Hung02701602022-07-15 09:35:36 +00006371 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6372 switch (fromSource) {
6373 case AINPUT_SOURCE_TOUCHSCREEN:
6374 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6375 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6376 ADISPLAY_ID_DEFAULT, {50, 50}))
6377 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6378 break;
6379 case AINPUT_SOURCE_STYLUS:
6380 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6381 injectMotionEvent(
6382 mDispatcher,
6383 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6384 AINPUT_SOURCE_STYLUS)
6385 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6386 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6387 .x(50)
6388 .y(50))
6389 .build()));
6390 break;
6391 case AINPUT_SOURCE_MOUSE:
6392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6393 injectMotionEvent(
6394 mDispatcher,
6395 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6396 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6397 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6398 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6399 .x(50)
6400 .y(50))
6401 .build()));
6402 break;
6403 default:
6404 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6405 }
arthurhungb89ccb02020-12-30 16:19:01 +08006406
6407 // Window should receive motion event.
6408 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006409 }
6410
6411 // Start performing drag, we will create a drag window and transfer touch to it.
6412 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6413 // Returns true on success.
Arthur Hung02701602022-07-15 09:35:36 +00006414 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006415 if (sendDown) {
Arthur Hung02701602022-07-15 09:35:36 +00006416 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006417 }
arthurhungb89ccb02020-12-30 16:19:01 +08006418
6419 // The drag window covers the entire display
6420 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6421 mDispatcher->setInputWindows(
6422 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6423
6424 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006425 bool transferred =
6426 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6427 true /* isDragDrop */);
6428 if (transferred) {
6429 mWindow->consumeMotionCancel();
6430 mDragWindow->consumeMotionDown();
6431 }
6432 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006433 }
6434};
6435
6436TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hung02701602022-07-15 09:35:36 +00006437 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006438
6439 // Move on window.
6440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6441 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6442 ADISPLAY_ID_DEFAULT, {50, 50}))
6443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6444 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6445 mWindow->consumeDragEvent(false, 50, 50);
6446 mSecondWindow->assertNoEvents();
6447
6448 // Move to another window.
6449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6450 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6451 ADISPLAY_ID_DEFAULT, {150, 50}))
6452 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6453 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6454 mWindow->consumeDragEvent(true, 150, 50);
6455 mSecondWindow->consumeDragEvent(false, 50, 50);
6456
6457 // Move back to original window.
6458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6459 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6460 ADISPLAY_ID_DEFAULT, {50, 50}))
6461 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6462 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6463 mWindow->consumeDragEvent(false, 50, 50);
6464 mSecondWindow->consumeDragEvent(true, -50, 50);
6465
6466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6467 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6468 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6469 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6470 mWindow->assertNoEvents();
6471 mSecondWindow->assertNoEvents();
6472}
6473
arthurhungf452d0b2021-01-06 00:19:52 +08006474TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006475 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006476
6477 // Move on window.
6478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6479 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6480 ADISPLAY_ID_DEFAULT, {50, 50}))
6481 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6482 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6483 mWindow->consumeDragEvent(false, 50, 50);
6484 mSecondWindow->assertNoEvents();
6485
6486 // Move to another window.
6487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6488 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6489 ADISPLAY_ID_DEFAULT, {150, 50}))
6490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6491 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6492 mWindow->consumeDragEvent(true, 150, 50);
6493 mSecondWindow->consumeDragEvent(false, 50, 50);
6494
6495 // drop to another window.
6496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6497 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6498 {150, 50}))
6499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6500 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6501 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6502 mWindow->assertNoEvents();
6503 mSecondWindow->assertNoEvents();
6504}
6505
arthurhung6d4bed92021-03-17 11:59:33 +08006506TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006507 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006508
6509 // Move on window and keep button pressed.
6510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6511 injectMotionEvent(mDispatcher,
6512 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6513 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6514 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6515 .x(50)
6516 .y(50))
6517 .build()))
6518 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6519 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6520 mWindow->consumeDragEvent(false, 50, 50);
6521 mSecondWindow->assertNoEvents();
6522
6523 // Move to another window and release button, expect to drop item.
6524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6525 injectMotionEvent(mDispatcher,
6526 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6527 .buttonState(0)
6528 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6529 .x(150)
6530 .y(50))
6531 .build()))
6532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6533 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6534 mWindow->assertNoEvents();
6535 mSecondWindow->assertNoEvents();
6536 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6537
6538 // nothing to the window.
6539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6540 injectMotionEvent(mDispatcher,
6541 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6542 .buttonState(0)
6543 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6544 .x(150)
6545 .y(50))
6546 .build()))
6547 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6548 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6549 mWindow->assertNoEvents();
6550 mSecondWindow->assertNoEvents();
6551}
6552
Arthur Hung54745652022-04-20 07:17:41 +00006553TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung02701602022-07-15 09:35:36 +00006554 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006555
6556 // Set second window invisible.
6557 mSecondWindow->setVisible(false);
6558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6559
6560 // Move on window.
6561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6562 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6563 ADISPLAY_ID_DEFAULT, {50, 50}))
6564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6565 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6566 mWindow->consumeDragEvent(false, 50, 50);
6567 mSecondWindow->assertNoEvents();
6568
6569 // Move to another window.
6570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6571 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6572 ADISPLAY_ID_DEFAULT, {150, 50}))
6573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6574 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6575 mWindow->consumeDragEvent(true, 150, 50);
6576 mSecondWindow->assertNoEvents();
6577
6578 // drop to another window.
6579 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6580 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6581 {150, 50}))
6582 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6583 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6584 mFakePolicy->assertDropTargetEquals(nullptr);
6585 mWindow->assertNoEvents();
6586 mSecondWindow->assertNoEvents();
6587}
6588
Arthur Hung54745652022-04-20 07:17:41 +00006589TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hung02701602022-07-15 09:35:36 +00006590 // Ensure window could track pointerIds if it didn't support split touch.
6591 mWindow->setPreventSplitting(true);
6592
Arthur Hung54745652022-04-20 07:17:41 +00006593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6595 {50, 50}))
6596 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6597 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6598
6599 const MotionEvent secondFingerDownEvent =
6600 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6601 .displayId(ADISPLAY_ID_DEFAULT)
6602 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6603 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6604 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6605 .build();
6606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6607 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6608 InputEventInjectionSync::WAIT_FOR_RESULT))
6609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6610 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6611
6612 // Should not perform drag and drop when window has multi fingers.
Arthur Hung02701602022-07-15 09:35:36 +00006613 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006614}
6615
6616TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6617 // First down on second window.
6618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6619 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6620 {150, 50}))
6621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6622
6623 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6624
6625 // Second down on first window.
6626 const MotionEvent secondFingerDownEvent =
6627 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6628 .displayId(ADISPLAY_ID_DEFAULT)
6629 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6630 .pointer(
6631 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6632 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6633 .build();
6634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6635 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6636 InputEventInjectionSync::WAIT_FOR_RESULT))
6637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6638 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6639
6640 // Perform drag and drop from first window.
Arthur Hung02701602022-07-15 09:35:36 +00006641 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006642
6643 // Move on window.
6644 const MotionEvent secondFingerMoveEvent =
6645 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6646 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6647 .pointer(
6648 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6649 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6650 .build();
6651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6652 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6653 InputEventInjectionSync::WAIT_FOR_RESULT));
6654 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6655 mWindow->consumeDragEvent(false, 50, 50);
6656 mSecondWindow->consumeMotionMove();
6657
6658 // Release the drag pointer should perform drop.
6659 const MotionEvent secondFingerUpEvent =
6660 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6661 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6662 .pointer(
6663 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6664 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6665 .build();
6666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6667 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6668 InputEventInjectionSync::WAIT_FOR_RESULT));
6669 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6670 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6671 mWindow->assertNoEvents();
6672 mSecondWindow->consumeMotionMove();
6673}
6674
Arthur Hung3915c1f2022-05-31 07:17:17 +00006675TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hung02701602022-07-15 09:35:36 +00006676 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006677
6678 // Update window of second display.
6679 sp<FakeWindowHandle> windowInSecondary =
6680 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6681 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6682
6683 // Let second display has a touch state.
6684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6685 injectMotionEvent(mDispatcher,
6686 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6687 AINPUT_SOURCE_TOUCHSCREEN)
6688 .displayId(SECOND_DISPLAY_ID)
6689 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6690 .x(100)
6691 .y(100))
6692 .build()));
6693 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6694 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6695 // Update window again.
6696 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6697
6698 // Move on window.
6699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6700 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6701 ADISPLAY_ID_DEFAULT, {50, 50}))
6702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6703 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6704 mWindow->consumeDragEvent(false, 50, 50);
6705 mSecondWindow->assertNoEvents();
6706
6707 // Move to another window.
6708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6709 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6710 ADISPLAY_ID_DEFAULT, {150, 50}))
6711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6712 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6713 mWindow->consumeDragEvent(true, 150, 50);
6714 mSecondWindow->consumeDragEvent(false, 50, 50);
6715
6716 // drop to another window.
6717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6718 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6719 {150, 50}))
6720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6721 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6722 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6723 mWindow->assertNoEvents();
6724 mSecondWindow->assertNoEvents();
6725}
6726
Arthur Hung02701602022-07-15 09:35:36 +00006727TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6728 startDrag(true, AINPUT_SOURCE_MOUSE);
6729 // Move on window.
6730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6731 injectMotionEvent(mDispatcher,
6732 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6733 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6734 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6735 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6736 .x(50)
6737 .y(50))
6738 .build()))
6739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6740 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6741 mWindow->consumeDragEvent(false, 50, 50);
6742 mSecondWindow->assertNoEvents();
6743
6744 // Move to another window.
6745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6746 injectMotionEvent(mDispatcher,
6747 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6748 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6749 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6750 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6751 .x(150)
6752 .y(50))
6753 .build()))
6754 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6755 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6756 mWindow->consumeDragEvent(true, 150, 50);
6757 mSecondWindow->consumeDragEvent(false, 50, 50);
6758
6759 // drop to another window.
6760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6761 injectMotionEvent(mDispatcher,
6762 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6763 .buttonState(0)
6764 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6765 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6766 .x(150)
6767 .y(50))
6768 .build()))
6769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6770 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6771 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6772 mWindow->assertNoEvents();
6773 mSecondWindow->assertNoEvents();
6774}
6775
Vishnu Nair062a8672021-09-03 16:07:44 -07006776class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6777
6778TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6779 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6780 sp<FakeWindowHandle> window =
6781 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006782 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006783 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6784 window->setFocusable(true);
6785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6786 setFocusedWindow(window);
6787 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6788
6789 // With the flag set, window should not get any input
6790 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6791 mDispatcher->notifyKey(&keyArgs);
6792 window->assertNoEvents();
6793
6794 NotifyMotionArgs motionArgs =
6795 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6796 ADISPLAY_ID_DEFAULT);
6797 mDispatcher->notifyMotion(&motionArgs);
6798 window->assertNoEvents();
6799
6800 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006801 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6803
6804 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6805 mDispatcher->notifyKey(&keyArgs);
6806 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6807
6808 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6809 ADISPLAY_ID_DEFAULT);
6810 mDispatcher->notifyMotion(&motionArgs);
6811 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6812 window->assertNoEvents();
6813}
6814
6815TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6816 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6817 std::make_shared<FakeApplicationHandle>();
6818 sp<FakeWindowHandle> obscuringWindow =
6819 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6820 ADISPLAY_ID_DEFAULT);
6821 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6822 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006823 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6825 sp<FakeWindowHandle> window =
6826 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006827 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006828 window->setOwnerInfo(222, 222);
6829 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6830 window->setFocusable(true);
6831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6832 setFocusedWindow(window);
6833 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6834
6835 // With the flag set, window should not get any input
6836 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6837 mDispatcher->notifyKey(&keyArgs);
6838 window->assertNoEvents();
6839
6840 NotifyMotionArgs motionArgs =
6841 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6842 ADISPLAY_ID_DEFAULT);
6843 mDispatcher->notifyMotion(&motionArgs);
6844 window->assertNoEvents();
6845
6846 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006847 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6849
6850 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6851 mDispatcher->notifyKey(&keyArgs);
6852 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6853
6854 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6855 ADISPLAY_ID_DEFAULT);
6856 mDispatcher->notifyMotion(&motionArgs);
6857 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6858 window->assertNoEvents();
6859}
6860
6861TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6862 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6863 std::make_shared<FakeApplicationHandle>();
6864 sp<FakeWindowHandle> obscuringWindow =
6865 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6866 ADISPLAY_ID_DEFAULT);
6867 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6868 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006869 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006870 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6871 sp<FakeWindowHandle> window =
6872 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006873 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006874 window->setOwnerInfo(222, 222);
6875 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6876 window->setFocusable(true);
6877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6878 setFocusedWindow(window);
6879 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6880
6881 // With the flag set, window should not get any input
6882 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6883 mDispatcher->notifyKey(&keyArgs);
6884 window->assertNoEvents();
6885
6886 NotifyMotionArgs motionArgs =
6887 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6888 ADISPLAY_ID_DEFAULT);
6889 mDispatcher->notifyMotion(&motionArgs);
6890 window->assertNoEvents();
6891
6892 // When the window is no longer obscured because it went on top, it should get input
6893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6894
6895 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6896 mDispatcher->notifyKey(&keyArgs);
6897 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6898
6899 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6900 ADISPLAY_ID_DEFAULT);
6901 mDispatcher->notifyMotion(&motionArgs);
6902 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6903 window->assertNoEvents();
6904}
6905
Antonio Kantekf16f2832021-09-28 04:39:20 +00006906class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6907protected:
6908 std::shared_ptr<FakeApplicationHandle> mApp;
6909 sp<FakeWindowHandle> mWindow;
6910 sp<FakeWindowHandle> mSecondWindow;
6911
6912 void SetUp() override {
6913 InputDispatcherTest::SetUp();
6914
6915 mApp = std::make_shared<FakeApplicationHandle>();
6916 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6917 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006918 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006919 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6920 mSecondWindow->setFocusable(true);
6921
6922 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006924 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006925
6926 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00006927 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6928 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006929 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6930 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6931 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006932 }
6933
Antonio Kantekea47acb2021-12-23 12:41:25 -08006934 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006935 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006936 mWindow->consumeTouchModeEvent(inTouchMode);
6937 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6938 }
6939};
6940
Antonio Kantek26defcf2022-02-08 01:12:27 +00006941TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006942 const WindowInfo& windowInfo = *mWindow->getInfo();
6943 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6944 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006945}
6946
Antonio Kantek26defcf2022-02-08 01:12:27 +00006947TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6948 const WindowInfo& windowInfo = *mWindow->getInfo();
6949 int32_t ownerPid = windowInfo.ownerPid;
6950 int32_t ownerUid = windowInfo.ownerUid;
6951 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6952 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6953 ownerUid, /* hasPermission */ false));
6954 mWindow->assertNoEvents();
6955 mSecondWindow->assertNoEvents();
6956}
6957
6958TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6959 const WindowInfo& windowInfo = *mWindow->getInfo();
6960 int32_t ownerPid = windowInfo.ownerPid;
6961 int32_t ownerUid = windowInfo.ownerUid;
6962 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6963 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6964 /* hasPermission */ true);
6965}
6966
Antonio Kantekf16f2832021-09-28 04:39:20 +00006967TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006968 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006969 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6970 windowInfo.ownerPid, windowInfo.ownerUid,
6971 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006972 mWindow->assertNoEvents();
6973 mSecondWindow->assertNoEvents();
6974}
6975
Antonio Kantek48710e42022-03-24 14:19:30 -07006976TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6977 // Interact with the window first.
6978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6979 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6980 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6981
6982 // Then remove focus.
6983 mWindow->setFocusable(false);
6984 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6985
6986 // Assert that caller can switch touch mode by owning one of the last interacted window.
6987 const WindowInfo& windowInfo = *mWindow->getInfo();
6988 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6989 windowInfo.ownerPid, windowInfo.ownerUid,
6990 /* hasPermission= */ false));
6991}
6992
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006993class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6994public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006995 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006996 std::shared_ptr<FakeApplicationHandle> application =
6997 std::make_shared<FakeApplicationHandle>();
6998 std::string name = "Fake Spy ";
6999 name += std::to_string(mSpyCount++);
7000 sp<FakeWindowHandle> spy =
7001 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007002 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007003 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007004 return spy;
7005 }
7006
7007 sp<FakeWindowHandle> createForeground() {
7008 std::shared_ptr<FakeApplicationHandle> application =
7009 std::make_shared<FakeApplicationHandle>();
7010 sp<FakeWindowHandle> window =
7011 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007012 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007013 return window;
7014 }
7015
7016private:
7017 int mSpyCount{0};
7018};
7019
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007020using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007021/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007022 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
7023 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007024TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
7025 ScopedSilentDeath _silentDeath;
7026
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007027 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007028 spy->setTrustedOverlay(false);
7029 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7030 ".* not a trusted overlay");
7031}
7032
7033/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007034 * Input injection into a display with a spy window but no foreground windows should succeed.
7035 */
7036TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007037 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7039
7040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7041 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7043 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7044}
7045
7046/**
7047 * Verify the order in which different input windows receive events. The touched foreground window
7048 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7049 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7050 * receive events before ones belows it.
7051 *
7052 * Here, we set up a scenario with four windows in the following Z order from the top:
7053 * spy1, spy2, window, spy3.
7054 * We then inject an event and verify that the foreground "window" receives it first, followed by
7055 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7056 * window.
7057 */
7058TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7059 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007060 auto spy1 = createSpy();
7061 auto spy2 = createSpy();
7062 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7064 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7065 const size_t numChannels = channels.size();
7066
Michael Wright8e9a8562022-02-09 13:44:29 +00007067 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007068 if (!epollFd.ok()) {
7069 FAIL() << "Failed to create epoll fd";
7070 }
7071
7072 for (size_t i = 0; i < numChannels; i++) {
7073 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7074 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7075 FAIL() << "Failed to add fd to epoll";
7076 }
7077 }
7078
7079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7080 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7082
7083 std::vector<size_t> eventOrder;
7084 std::vector<struct epoll_event> events(numChannels);
7085 for (;;) {
7086 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7087 (100ms).count());
7088 if (nFds < 0) {
7089 FAIL() << "Failed to call epoll_wait";
7090 }
7091 if (nFds == 0) {
7092 break; // epoll_wait timed out
7093 }
7094 for (int i = 0; i < nFds; i++) {
7095 ASSERT_EQ(EPOLLIN, events[i].events);
7096 eventOrder.push_back(events[i].data.u64);
7097 channels[i]->consumeMotionDown();
7098 }
7099 }
7100
7101 // Verify the order in which the events were received.
7102 EXPECT_EQ(3u, eventOrder.size());
7103 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7104 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7105 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7106}
7107
7108/**
7109 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7110 */
7111TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7112 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007113 auto spy = createSpy();
7114 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7116
7117 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7118 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7120 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7121 spy->assertNoEvents();
7122}
7123
7124/**
7125 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7126 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7127 * to the window.
7128 */
7129TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7130 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007131 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007132 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7134
7135 // Inject an event outside the spy window's touchable region.
7136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7137 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7138 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7139 window->consumeMotionDown();
7140 spy->assertNoEvents();
7141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7142 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7143 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7144 window->consumeMotionUp();
7145 spy->assertNoEvents();
7146
7147 // Inject an event inside the spy window's touchable region.
7148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7149 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7150 {5, 10}))
7151 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7152 window->consumeMotionDown();
7153 spy->consumeMotionDown();
7154}
7155
7156/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007157 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007158 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007159 */
7160TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7161 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007162 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007163 auto spy = createSpy();
7164 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007165 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007166 spy->setFrame(Rect{0, 0, 20, 20});
7167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7168
7169 // Inject an event outside the spy window's frame and touchable region.
7170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007171 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7172 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007173 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7174 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007175 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007176}
7177
7178/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007179 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
7180 * any other windows - including other spy windows - will also be cancelled.
7181 */
7182TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
7183 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007184 auto spy1 = createSpy();
7185 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7187
7188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7189 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7190 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7191 window->consumeMotionDown();
7192 spy1->consumeMotionDown();
7193 spy2->consumeMotionDown();
7194
7195 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007196 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007197 spy2->assertNoEvents();
7198 spy1->consumeMotionCancel();
7199 window->consumeMotionCancel();
7200
7201 // The rest of the gesture should only be sent to the second spy window.
7202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7203 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7204 ADISPLAY_ID_DEFAULT))
7205 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7206 spy2->consumeMotionMove();
7207 spy1->assertNoEvents();
7208 window->assertNoEvents();
7209}
7210
7211/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007212 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7213 * in the middle of the gesture.
7214 */
7215TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
7216 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007217 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7219
7220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7221 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7222 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7223 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7224 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7225
7226 window->releaseChannel();
7227
7228 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7229
7230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7231 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7232 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7233 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7234}
7235
7236/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007237 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7238 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007239 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007240TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007241 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007242 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007243
7244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7245
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007246 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7248 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7249 {100, 200}))
7250 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007251 spy->consumeMotionDown();
7252 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007253
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007254 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007255 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007256 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007257
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007258 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007259 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007260 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007261 .displayId(ADISPLAY_ID_DEFAULT)
7262 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7263 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7264 .x(100)
7265 .y(200))
7266 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7267 .build();
7268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7269 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7270 InputEventInjectionSync::WAIT_FOR_RESULT))
7271 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7272
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007273 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7274
7275 // Third finger goes down outside all windows, so injection should fail.
7276 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00007277 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007278 .displayId(ADISPLAY_ID_DEFAULT)
7279 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7280 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7281 .x(100)
7282 .y(200))
7283 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7284 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7285 .build();
7286 ASSERT_EQ(InputEventInjectionResult::FAILED,
7287 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7288 InputEventInjectionSync::WAIT_FOR_RESULT))
7289 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7290
7291 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007292 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007293}
7294
7295/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007296 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7297 * pointers that are down within its bounds.
7298 */
7299TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7300 auto windowLeft = createForeground();
7301 windowLeft->setFrame({0, 0, 100, 200});
7302 auto windowRight = createForeground();
7303 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007304 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007305 spy->setFrame({0, 0, 200, 200});
7306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7307
7308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7309 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7310 {50, 50}))
7311 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7312 windowLeft->consumeMotionDown();
7313 spy->consumeMotionDown();
7314
7315 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007316 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007317 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7318 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7319 .pointer(
7320 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7321 .build();
7322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7323 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7324 InputEventInjectionSync::WAIT_FOR_RESULT))
7325 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7326 windowRight->consumeMotionDown();
7327 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7328}
7329
7330/**
7331 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7332 * the spy should receive the second pointer with ACTION_DOWN.
7333 */
7334TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7335 auto window = createForeground();
7336 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007337 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007338 spyRight->setFrame({100, 0, 200, 200});
7339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7340
7341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7343 {50, 50}))
7344 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7345 window->consumeMotionDown();
7346 spyRight->assertNoEvents();
7347
7348 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007349 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007350 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7351 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7352 .pointer(
7353 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7354 .build();
7355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7356 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7357 InputEventInjectionSync::WAIT_FOR_RESULT))
7358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7359 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7360 spyRight->consumeMotionDown();
7361}
7362
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007363/**
7364 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7365 * windows should be allowed to control split touch.
7366 */
7367TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007368 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007369 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007370 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007371 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007372
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007373 auto window = createForeground();
7374 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007375
7376 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7377
7378 // First finger down, no window touched.
7379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7381 {100, 200}))
7382 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7383 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7384 window->assertNoEvents();
7385
7386 // Second finger down on window, the window should receive touch down.
7387 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007388 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007389 .displayId(ADISPLAY_ID_DEFAULT)
7390 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7391 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7392 .x(100)
7393 .y(200))
7394 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7395 .build();
7396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7397 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7398 InputEventInjectionSync::WAIT_FOR_RESULT))
7399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7400
7401 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7402 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7403}
7404
7405/**
7406 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7407 * do not receive key events.
7408 */
7409TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007410 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007411 spy->setFocusable(false);
7412
7413 auto window = createForeground();
7414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7415 setFocusedWindow(window);
7416 window->consumeFocusEvent(true);
7417
7418 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7419 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7420 window->consumeKeyDown(ADISPLAY_ID_NONE);
7421
7422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7423 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7424 window->consumeKeyUp(ADISPLAY_ID_NONE);
7425
7426 spy->assertNoEvents();
7427}
7428
Prabir Pradhand65552b2021-10-07 11:23:50 -07007429class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7430public:
7431 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7432 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7433 std::make_shared<FakeApplicationHandle>();
7434 sp<FakeWindowHandle> overlay =
7435 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7436 ADISPLAY_ID_DEFAULT);
7437 overlay->setFocusable(false);
7438 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007439 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007440 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007441 overlay->setTrustedOverlay(true);
7442
7443 std::shared_ptr<FakeApplicationHandle> application =
7444 std::make_shared<FakeApplicationHandle>();
7445 sp<FakeWindowHandle> window =
7446 new FakeWindowHandle(application, mDispatcher, "Application window",
7447 ADISPLAY_ID_DEFAULT);
7448 window->setFocusable(true);
7449 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007450
7451 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7453 setFocusedWindow(window);
7454 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7455 return {std::move(overlay), std::move(window)};
7456 }
7457
7458 void sendFingerEvent(int32_t action) {
7459 NotifyMotionArgs motionArgs =
7460 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7461 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7462 mDispatcher->notifyMotion(&motionArgs);
7463 }
7464
7465 void sendStylusEvent(int32_t action) {
7466 NotifyMotionArgs motionArgs =
7467 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7468 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7469 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7470 mDispatcher->notifyMotion(&motionArgs);
7471 }
7472};
7473
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007474using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7475
7476TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7477 ScopedSilentDeath _silentDeath;
7478
Prabir Pradhand65552b2021-10-07 11:23:50 -07007479 auto [overlay, window] = setupStylusOverlayScenario();
7480 overlay->setTrustedOverlay(false);
7481 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7482 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7483 ".* not a trusted overlay");
7484}
7485
7486TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7487 auto [overlay, window] = setupStylusOverlayScenario();
7488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7489
7490 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7491 overlay->consumeMotionDown();
7492 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7493 overlay->consumeMotionUp();
7494
7495 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7496 window->consumeMotionDown();
7497 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7498 window->consumeMotionUp();
7499
7500 overlay->assertNoEvents();
7501 window->assertNoEvents();
7502}
7503
7504TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7505 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007506 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7508
7509 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7510 overlay->consumeMotionDown();
7511 window->consumeMotionDown();
7512 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7513 overlay->consumeMotionUp();
7514 window->consumeMotionUp();
7515
7516 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7517 window->consumeMotionDown();
7518 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7519 window->consumeMotionUp();
7520
7521 overlay->assertNoEvents();
7522 window->assertNoEvents();
7523}
7524
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007525/**
7526 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7527 * The scenario is as follows:
7528 * - The stylus interceptor overlay is configured as a spy window.
7529 * - The stylus interceptor spy receives the start of a new stylus gesture.
7530 * - It pilfers pointers and then configures itself to no longer be a spy.
7531 * - The stylus interceptor continues to receive the rest of the gesture.
7532 */
7533TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7534 auto [overlay, window] = setupStylusOverlayScenario();
7535 overlay->setSpy(true);
7536 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7537
7538 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7539 overlay->consumeMotionDown();
7540 window->consumeMotionDown();
7541
7542 // The interceptor pilfers the pointers.
7543 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7544 window->consumeMotionCancel();
7545
7546 // The interceptor configures itself so that it is no longer a spy.
7547 overlay->setSpy(false);
7548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7549
7550 // It continues to receive the rest of the stylus gesture.
7551 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7552 overlay->consumeMotionMove();
7553 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7554 overlay->consumeMotionUp();
7555
7556 window->assertNoEvents();
7557}
7558
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007559struct User {
7560 int32_t mPid;
7561 int32_t mUid;
7562 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7563 std::unique_ptr<InputDispatcher>& mDispatcher;
7564
7565 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7566 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7567
7568 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7569 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7570 ADISPLAY_ID_DEFAULT, {100, 200},
7571 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7572 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7573 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7574 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7575 }
7576
7577 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7578 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7579 InputEventInjectionSync::WAIT_FOR_RESULT,
7580 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7581 mPolicyFlags);
7582 }
7583
7584 sp<FakeWindowHandle> createWindow() const {
7585 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7586 std::make_shared<FakeApplicationHandle>();
7587 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7588 "Owned Window", ADISPLAY_ID_DEFAULT);
7589 window->setOwnerInfo(mPid, mUid);
7590 return window;
7591 }
7592};
7593
7594using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7595
7596TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7597 auto owner = User(mDispatcher, 10, 11);
7598 auto window = owner.createWindow();
7599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7600
7601 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7602 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7603 window->consumeMotionDown();
7604
7605 setFocusedWindow(window);
7606 window->consumeFocusEvent(true);
7607
7608 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7609 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7610 window->consumeKeyDown(ADISPLAY_ID_NONE);
7611}
7612
7613TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7614 auto owner = User(mDispatcher, 10, 11);
7615 auto window = owner.createWindow();
7616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7617
7618 auto rando = User(mDispatcher, 20, 21);
7619 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7620 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7621
7622 setFocusedWindow(window);
7623 window->consumeFocusEvent(true);
7624
7625 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7626 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7627 window->assertNoEvents();
7628}
7629
7630TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7631 auto owner = User(mDispatcher, 10, 11);
7632 auto window = owner.createWindow();
7633 auto spy = owner.createWindow();
7634 spy->setSpy(true);
7635 spy->setTrustedOverlay(true);
7636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7637
7638 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7639 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7640 spy->consumeMotionDown();
7641 window->consumeMotionDown();
7642}
7643
7644TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7645 auto owner = User(mDispatcher, 10, 11);
7646 auto window = owner.createWindow();
7647
7648 auto rando = User(mDispatcher, 20, 21);
7649 auto randosSpy = rando.createWindow();
7650 randosSpy->setSpy(true);
7651 randosSpy->setTrustedOverlay(true);
7652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7653
7654 // The event is targeted at owner's window, so injection should succeed, but the spy should
7655 // not receive the event.
7656 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7657 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7658 randosSpy->assertNoEvents();
7659 window->consumeMotionDown();
7660}
7661
7662TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7663 auto owner = User(mDispatcher, 10, 11);
7664 auto window = owner.createWindow();
7665
7666 auto rando = User(mDispatcher, 20, 21);
7667 auto randosSpy = rando.createWindow();
7668 randosSpy->setSpy(true);
7669 randosSpy->setTrustedOverlay(true);
7670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7671
7672 // A user that has injection permission can inject into any window.
7673 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7674 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7675 ADISPLAY_ID_DEFAULT));
7676 randosSpy->consumeMotionDown();
7677 window->consumeMotionDown();
7678
7679 setFocusedWindow(randosSpy);
7680 randosSpy->consumeFocusEvent(true);
7681
7682 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7683 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7684 window->assertNoEvents();
7685}
7686
7687TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7688 auto owner = User(mDispatcher, 10, 11);
7689 auto window = owner.createWindow();
7690
7691 auto rando = User(mDispatcher, 20, 21);
7692 auto randosWindow = rando.createWindow();
7693 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7694 randosWindow->setWatchOutsideTouch(true);
7695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7696
7697 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7698 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7699 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7700 window->consumeMotionDown();
7701 randosWindow->consumeMotionOutside();
7702}
7703
Garfield Tane84e6f92019-08-29 17:28:41 -07007704} // namespace android::inputdispatcher