blob: 4977c39b2f57e12c7e97952702d30ad6e0f75a40 [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);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080061static constexpr int32_t POINTER_1_UP =
62 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
63
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000064// The default pid and uid for windows created by the test.
65static constexpr int32_t WINDOW_PID = 999;
66static constexpr int32_t WINDOW_UID = 1001;
67
68// The default policy flags to use for event injection by tests.
69static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000071// An arbitrary pid of the gesture monitor window
72static constexpr int32_t MONITOR_PID = 2001;
73
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080074static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
75
chaviwd1c23182019-12-20 18:44:56 -080076struct PointF {
77 float x;
78 float y;
79};
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
Gang Wang342c9272020-01-13 13:15:04 -050081/**
82 * Return a DOWN key event with KEYCODE_A.
83 */
84static KeyEvent getTestKeyEvent() {
85 KeyEvent event;
86
Garfield Tanfbe732e2020-01-24 11:26:14 -080087 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
88 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
89 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050090 return event;
91}
92
Siarhei Vishniakouca205502021-07-16 21:31:58 +000093static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
94 ASSERT_EQ(expectedAction, receivedAction)
95 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
96 << MotionEvent::actionToString(receivedAction);
97}
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099// --- FakeInputDispatcherPolicy ---
100
101class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
102 InputDispatcherConfiguration mConfig;
103
Prabir Pradhanedd96402022-02-15 01:46:16 -0800104 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000107 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108
109public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000110 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800111
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800112 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700113 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
114 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
115 EXPECT_EQ(event.getDisplayId(), args.displayId);
116
117 const auto& keyEvent = static_cast<const KeyEvent&>(event);
118 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
119 EXPECT_EQ(keyEvent.getAction(), args.action);
120 });
Jackal Guof9696682018-10-05 12:23:23 +0800121 }
122
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700123 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
124 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
125 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
126 EXPECT_EQ(event.getDisplayId(), args.displayId);
127
128 const auto& motionEvent = static_cast<const MotionEvent&>(event);
129 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
130 EXPECT_EQ(motionEvent.getAction(), args.action);
131 EXPECT_EQ(motionEvent.getX(0), point.x);
132 EXPECT_EQ(motionEvent.getY(0), point.y);
133 EXPECT_EQ(motionEvent.getRawX(0), point.x);
134 EXPECT_EQ(motionEvent.getRawY(0), point.y);
135 });
Jackal Guof9696682018-10-05 12:23:23 +0800136 }
137
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700138 void assertFilterInputEventWasNotCalled() {
139 std::scoped_lock lock(mLock);
140 ASSERT_EQ(nullptr, mFilteredEvent);
141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800143 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700144 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800145 ASSERT_TRUE(mConfigurationChangedTime)
146 << "Timed out waiting for configuration changed call";
147 ASSERT_EQ(*mConfigurationChangedTime, when);
148 mConfigurationChangedTime = std::nullopt;
149 }
150
151 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700152 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800153 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800154 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800155 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
156 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
157 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
158 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
159 mLastNotifySwitch = std::nullopt;
160 }
161
chaviwfd6d3512019-03-25 13:23:49 -0700162 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700163 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800164 ASSERT_EQ(touchedToken, mOnPointerDownToken);
165 mOnPointerDownToken.clear();
166 }
167
168 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700169 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800170 ASSERT_TRUE(mOnPointerDownToken == nullptr)
171 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700172 }
173
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700174 // This function must be called soon after the expected ANR timer starts,
175 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700177 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800179 std::unique_lock lock(mLock);
180 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500181 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800182 ASSERT_NO_FATAL_FAILURE(
183 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500184 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700185 }
186
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000187 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800188 const sp<WindowInfoHandle>& window) {
189 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
190 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
191 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500192 }
193
Prabir Pradhanedd96402022-02-15 01:46:16 -0800194 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
195 const sp<IBinder>& expectedToken,
196 int32_t expectedPid) {
197 std::unique_lock lock(mLock);
198 android::base::ScopedLockAssertion assumeLocked(mLock);
199 AnrResult result;
200 ASSERT_NO_FATAL_FAILURE(result =
201 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
202 const auto& [token, pid] = result;
203 ASSERT_EQ(expectedToken, token);
204 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500205 }
206
Prabir Pradhanedd96402022-02-15 01:46:16 -0800207 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500209 std::unique_lock lock(mLock);
210 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800211 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
212 const auto& [token, _] = result;
213 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000214 }
215
Prabir Pradhanedd96402022-02-15 01:46:16 -0800216 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
217 int32_t expectedPid) {
218 std::unique_lock lock(mLock);
219 android::base::ScopedLockAssertion assumeLocked(mLock);
220 AnrResult result;
221 ASSERT_NO_FATAL_FAILURE(
222 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
223 const auto& [token, pid] = result;
224 ASSERT_EQ(expectedToken, token);
225 ASSERT_EQ(expectedPid, pid);
226 }
227
228 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000229 sp<IBinder> getResponsiveWindowToken() {
230 std::unique_lock lock(mLock);
231 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800232 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
233 const auto& [token, _] = result;
234 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700235 }
236
237 void assertNotifyAnrWasNotCalled() {
238 std::scoped_lock lock(mLock);
239 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800240 ASSERT_TRUE(mAnrWindows.empty());
241 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500242 << "ANR was not called, but please also consume the 'connection is responsive' "
243 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700244 }
245
Garfield Tan1c7bc862020-01-28 13:24:04 -0800246 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
247 mConfig.keyRepeatTimeout = timeout;
248 mConfig.keyRepeatDelay = delay;
249 }
250
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000251 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800252 std::unique_lock lock(mLock);
253 base::ScopedLockAssertion assumeLocked(mLock);
254
255 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
256 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000257 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800258 enabled;
259 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000260 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
261 << ") to be called.";
262 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800263 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000264 auto request = *mPointerCaptureRequest;
265 mPointerCaptureRequest.reset();
266 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800267 }
268
269 void assertSetPointerCaptureNotCalled() {
270 std::unique_lock lock(mLock);
271 base::ScopedLockAssertion assumeLocked(mLock);
272
273 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000274 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800275 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000276 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800277 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800279 }
280
arthurhungf452d0b2021-01-06 00:19:52 +0800281 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
282 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800283 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800284 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800285 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800286 }
287
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800288 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
289 std::unique_lock lock(mLock);
290 base::ScopedLockAssertion assumeLocked(mLock);
291 std::optional<sp<IBinder>> receivedToken =
292 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
293 mNotifyInputChannelBroken);
294 ASSERT_TRUE(receivedToken.has_value());
295 ASSERT_EQ(token, *receivedToken);
296 }
297
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800298 /**
299 * Set policy timeout. A value of zero means next key will not be intercepted.
300 */
301 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
302 mInterceptKeyTimeout = timeout;
303 }
304
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700306 std::mutex mLock;
307 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
308 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
309 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
310 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800311
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000313
314 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800315
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700316 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700317 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800318 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
319 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700320 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800321 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
322 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700323
arthurhungf452d0b2021-01-06 00:19:52 +0800324 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800325 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800326
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800327 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
328
Prabir Pradhanedd96402022-02-15 01:46:16 -0800329 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
330 // for a specific container to become non-empty. When the container is non-empty, return the
331 // first entry from the container and erase it.
332 template <class T>
333 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
334 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
335 // If there is an ANR, Dispatcher won't be idle because there are still events
336 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
337 // before checking if ANR was called.
338 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
339 // to provide it some time to act. 100ms seems reasonable.
340 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
341 const std::chrono::time_point start = std::chrono::steady_clock::now();
342 std::optional<T> token =
343 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
344 if (!token.has_value()) {
345 ADD_FAILURE() << "Did not receive the ANR callback";
346 return {};
347 }
348
349 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
350 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
351 // the dispatcher started counting before this function was called
352 if (std::chrono::abs(timeout - waited) > 100ms) {
353 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
354 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
355 << "ms, but waited "
356 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
357 << "ms instead";
358 }
359 return *token;
360 }
361
362 template <class T>
363 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
364 std::queue<T>& storage,
365 std::unique_lock<std::mutex>& lock,
366 std::condition_variable& condition)
367 REQUIRES(mLock) {
368 condition.wait_for(lock, timeout,
369 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
370 if (storage.empty()) {
371 ADD_FAILURE() << "Did not receive the expected callback";
372 return std::nullopt;
373 }
374 T item = storage.front();
375 storage.pop();
376 return std::make_optional(item);
377 }
378
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600379 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700380 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800381 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
Prabir Pradhanedd96402022-02-15 01:46:16 -0800384 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
385 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700386 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800387 ASSERT_TRUE(pid.has_value());
388 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700389 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500390 }
391
Prabir Pradhanedd96402022-02-15 01:46:16 -0800392 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
393 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500394 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800395 ASSERT_TRUE(pid.has_value());
396 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500397 mNotifyAnr.notify_all();
398 }
399
400 void notifyNoFocusedWindowAnr(
401 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
402 std::scoped_lock lock(mLock);
403 mAnrApplications.push(applicationHandle);
404 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 }
406
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800407 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
408 std::scoped_lock lock(mLock);
409 mBrokenInputChannels.push(connectionToken);
410 mNotifyInputChannelBroken.notify_all();
411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600413 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700416 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
417 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
418 const std::vector<float>& values) override {}
419
420 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
421 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000422
Chris Yefb552902021-02-03 17:18:37 -0800423 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
424
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600425 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 *outConfig = mConfig;
427 }
428
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600429 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700430 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800431 switch (inputEvent->getType()) {
432 case AINPUT_EVENT_TYPE_KEY: {
433 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800434 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800435 break;
436 }
437
438 case AINPUT_EVENT_TYPE_MOTION: {
439 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800440 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800441 break;
442 }
443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 return true;
445 }
446
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800447 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
448 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
449 // Clear intercept state when we handled the event.
450 mInterceptKeyTimeout = 0ms;
451 }
452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600454 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600456 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800457 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
458 // Clear intercept state so we could dispatch the event in next wake.
459 mInterceptKeyTimeout = 0ms;
460 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 }
462
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600463 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 return false;
465 }
466
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600467 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
468 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700469 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
471 * essentially a passthrough for notifySwitch.
472 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800473 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 }
475
Sean Stoutb4e0a592021-02-23 07:34:53 -0800476 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600478 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700479 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700480 mOnPointerDownToken = newToken;
481 }
482
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000483 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800484 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000485 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800486 mPointerCaptureChangedCondition.notify_all();
487 }
488
arthurhungf452d0b2021-01-06 00:19:52 +0800489 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
490 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800491 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800492 mDropTargetWindowToken = token;
493 }
494
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700495 void assertFilterInputEventWasCalledInternal(
496 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700497 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800498 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700499 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800500 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502};
503
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504// --- InputDispatcherTest ---
505
506class InputDispatcherTest : public testing::Test {
507protected:
508 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700509 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000511 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800513 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800514 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000515 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700516 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 }
518
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000519 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700520 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700522 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700524
525 /**
526 * Used for debugging when writing the test
527 */
528 void dumpDispatcherState() {
529 std::string dump;
530 mDispatcher->dump(dump);
531 std::stringstream ss(dump);
532 std::string to;
533
534 while (std::getline(ss, to, '\n')) {
535 ALOGE("%s", to.c_str());
536 }
537 }
Vishnu Nair958da932020-08-21 17:12:37 -0700538
chaviw3277faf2021-05-19 16:45:23 -0500539 void setFocusedWindow(const sp<WindowInfoHandle>& window,
540 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700541 FocusRequest request;
542 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000543 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700544 if (focusedWindow) {
545 request.focusedToken = focusedWindow->getToken();
546 }
547 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
548 request.displayId = window->getInfo()->displayId;
549 mDispatcher->setFocusedWindow(request);
550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551};
552
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
554 KeyEvent event;
555
556 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800557 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
558 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600559 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
560 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000562 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
563 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 << "Should reject key events with undefined action.";
565
566 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
568 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600569 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800570 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000571 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
572 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 << "Should reject key events with ACTION_MULTIPLE.";
574}
575
576TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
577 MotionEvent event;
578 PointerProperties pointerProperties[MAX_POINTERS + 1];
579 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800580 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 pointerProperties[i].clear();
582 pointerProperties[i].id = i;
583 pointerCoords[i].clear();
584 }
585
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800586 // Some constants commonly used below
587 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
588 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
589 constexpr int32_t metaState = AMETA_NONE;
590 constexpr MotionClassification classification = MotionClassification::NONE;
591
chaviw9eaa22c2020-07-01 16:21:27 -0700592 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800594 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700595 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
596 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700597 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
598 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800600 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000601 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
602 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 << "Should reject motion events with undefined action.";
604
605 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800606 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800607 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
608 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
609 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
610 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500611 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000613 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
614 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 << "Should reject motion events with pointer down index too large.";
616
Garfield Tanfbe732e2020-01-24 11:26:14 -0800617 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700618 AMOTION_EVENT_ACTION_POINTER_DOWN |
619 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700620 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
621 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700622 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500623 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000625 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
626 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 << "Should reject motion events with pointer down index too small.";
628
629 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800630 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800631 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
632 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
633 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
634 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500635 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000637 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
638 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 << "Should reject motion events with pointer up index too large.";
640
Garfield Tanfbe732e2020-01-24 11:26:14 -0800641 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700642 AMOTION_EVENT_ACTION_POINTER_UP |
643 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700644 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
645 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700646 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500647 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800648 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000649 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
650 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 << "Should reject motion events with pointer up index too small.";
652
653 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800654 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
655 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700656 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700657 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
658 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700659 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000661 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
662 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 << "Should reject motion events with 0 pointers.";
664
Garfield Tanfbe732e2020-01-24 11:26:14 -0800665 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
666 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700667 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700668 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
669 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700670 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000672 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
673 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 << "Should reject motion events with more than MAX_POINTERS pointers.";
675
676 // Rejects motion events with invalid pointer ids.
677 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800678 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
679 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700680 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700681 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
682 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700683 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800684 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000685 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
686 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 << "Should reject motion events with pointer ids less than 0.";
688
689 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800690 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
691 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700692 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700693 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
694 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700695 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800696 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000697 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
698 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
700
701 // Rejects motion events with duplicate pointer ids.
702 pointerProperties[0].id = 1;
703 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800704 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
705 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700706 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700707 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
708 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700709 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800710 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000711 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
712 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 << "Should reject motion events with duplicate pointer ids.";
714}
715
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800716/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
717
718TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
719 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800720 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800721 mDispatcher->notifyConfigurationChanged(&args);
722 ASSERT_TRUE(mDispatcher->waitForIdle());
723
724 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
725}
726
727TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800728 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
729 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800730 mDispatcher->notifySwitch(&args);
731
732 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
733 args.policyFlags |= POLICY_FLAG_TRUSTED;
734 mFakePolicy->assertNotifySwitchWasCalled(args);
735}
736
Arthur Hungb92218b2018-08-14 12:00:21 +0800737// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700738static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700739// Default input dispatching timeout if there is no focused application or paused window
740// from which to determine an appropriate dispatching timeout.
741static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
742 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
743 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800744
745class FakeApplicationHandle : public InputApplicationHandle {
746public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700747 FakeApplicationHandle() {
748 mInfo.name = "Fake Application";
749 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500750 mInfo.dispatchingTimeoutMillis =
751 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800753 virtual ~FakeApplicationHandle() {}
754
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000755 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700756
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500757 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
758 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700759 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800760};
761
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800762class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800763public:
Garfield Tan15601662020-09-22 15:32:38 -0700764 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800765 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700766 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800767 }
768
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800769 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700770 InputEvent* event;
771 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
772 if (!consumeSeq) {
773 return nullptr;
774 }
775 finishEvent(*consumeSeq);
776 return event;
777 }
778
779 /**
780 * Receive an event without acknowledging it.
781 * Return the sequence number that could later be used to send finished signal.
782 */
783 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800784 uint32_t consumeSeq;
785 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800786
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800787 std::chrono::time_point start = std::chrono::steady_clock::now();
788 status_t status = WOULD_BLOCK;
789 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800790 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800791 &event);
792 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
793 if (elapsed > 100ms) {
794 break;
795 }
796 }
797
798 if (status == WOULD_BLOCK) {
799 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700800 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800801 }
802
803 if (status != OK) {
804 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700805 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800806 }
807 if (event == nullptr) {
808 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700809 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800810 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700811 if (outEvent != nullptr) {
812 *outEvent = event;
813 }
814 return consumeSeq;
815 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700817 /**
818 * To be used together with "receiveEvent" to complete the consumption of an event.
819 */
820 void finishEvent(uint32_t consumeSeq) {
821 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
822 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800823 }
824
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000825 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
826 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
827 ASSERT_EQ(OK, status);
828 }
829
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000830 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
831 std::optional<int32_t> expectedDisplayId,
832 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800833 InputEvent* event = consume();
834
835 ASSERT_NE(nullptr, event) << mName.c_str()
836 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800837 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800839 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800840
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000841 if (expectedDisplayId.has_value()) {
842 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
843 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800844
Tiger Huang8664f8c2018-10-11 19:14:35 +0800845 switch (expectedEventType) {
846 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800847 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
848 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000849 if (expectedFlags.has_value()) {
850 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
851 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800852 break;
853 }
854 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800855 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000856 assertMotionAction(expectedAction, motionEvent.getAction());
857
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000858 if (expectedFlags.has_value()) {
859 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
860 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800861 break;
862 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100863 case AINPUT_EVENT_TYPE_FOCUS: {
864 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
865 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800866 case AINPUT_EVENT_TYPE_CAPTURE: {
867 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
868 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000869 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
870 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
871 }
arthurhungb89ccb02020-12-30 16:19:01 +0800872 case AINPUT_EVENT_TYPE_DRAG: {
873 FAIL() << "Use 'consumeDragEvent' for DRAG events";
874 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800875 default: {
876 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
877 }
878 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800879 }
880
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100881 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
882 InputEvent* event = consume();
883 ASSERT_NE(nullptr, event) << mName.c_str()
884 << ": consumer should have returned non-NULL event.";
885 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
886 << "Got " << inputEventTypeToString(event->getType())
887 << " event instead of FOCUS event";
888
889 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
890 << mName.c_str() << ": event displayId should always be NONE.";
891
892 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
893 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100894 }
895
Prabir Pradhan99987712020-11-10 18:43:05 -0800896 void consumeCaptureEvent(bool hasCapture) {
897 const InputEvent* event = consume();
898 ASSERT_NE(nullptr, event) << mName.c_str()
899 << ": consumer should have returned non-NULL event.";
900 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
901 << "Got " << inputEventTypeToString(event->getType())
902 << " event instead of CAPTURE event";
903
904 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
905 << mName.c_str() << ": event displayId should always be NONE.";
906
907 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
908 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
909 }
910
arthurhungb89ccb02020-12-30 16:19:01 +0800911 void consumeDragEvent(bool isExiting, float x, float y) {
912 const InputEvent* event = consume();
913 ASSERT_NE(nullptr, event) << mName.c_str()
914 << ": consumer should have returned non-NULL event.";
915 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
916 << "Got " << inputEventTypeToString(event->getType())
917 << " event instead of DRAG event";
918
919 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
920 << mName.c_str() << ": event displayId should always be NONE.";
921
922 const auto& dragEvent = static_cast<const DragEvent&>(*event);
923 EXPECT_EQ(isExiting, dragEvent.isExiting());
924 EXPECT_EQ(x, dragEvent.getX());
925 EXPECT_EQ(y, dragEvent.getY());
926 }
927
Antonio Kantekf16f2832021-09-28 04:39:20 +0000928 void consumeTouchModeEvent(bool inTouchMode) {
929 const InputEvent* event = consume();
930 ASSERT_NE(nullptr, event) << mName.c_str()
931 << ": consumer should have returned non-NULL event.";
932 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
933 << "Got " << inputEventTypeToString(event->getType())
934 << " event instead of TOUCH_MODE event";
935
936 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
937 << mName.c_str() << ": event displayId should always be NONE.";
938 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
939 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
940 }
941
chaviwd1c23182019-12-20 18:44:56 -0800942 void assertNoEvents() {
943 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 if (event == nullptr) {
945 return;
946 }
947 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
948 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
949 ADD_FAILURE() << "Received key event "
950 << KeyEvent::actionToString(keyEvent.getAction());
951 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
952 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
953 ADD_FAILURE() << "Received motion event "
954 << MotionEvent::actionToString(motionEvent.getAction());
955 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
956 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
957 ADD_FAILURE() << "Received focus event, hasFocus = "
958 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800959 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
960 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
961 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
962 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000963 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
964 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
965 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
966 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967 }
968 FAIL() << mName.c_str()
969 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800970 }
971
972 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
973
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800974 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
975
chaviwd1c23182019-12-20 18:44:56 -0800976protected:
977 std::unique_ptr<InputConsumer> mConsumer;
978 PreallocatedInputEventFactory mEventFactory;
979
980 std::string mName;
981};
982
chaviw3277faf2021-05-19 16:45:23 -0500983class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800984public:
985 static const int32_t WIDTH = 600;
986 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800987
Chris Yea209fde2020-07-22 13:54:51 -0700988 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700989 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500990 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800991 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500992 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700993 base::Result<std::unique_ptr<InputChannel>> channel =
994 dispatcher->createInputChannel(name);
995 token = (*channel)->getConnectionToken();
996 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800997 }
998
999 inputApplicationHandle->updateInfo();
1000 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1001
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001002 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001003 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001004 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001005 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001006 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001007 mInfo.frameLeft = 0;
1008 mInfo.frameTop = 0;
1009 mInfo.frameRight = WIDTH;
1010 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001011 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001012 mInfo.globalScaleFactor = 1.0;
1013 mInfo.touchableRegion.clear();
1014 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001015 mInfo.ownerPid = WINDOW_PID;
1016 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001017 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001018 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001019 }
1020
Arthur Hungabbb9d82021-09-01 14:52:30 +00001021 sp<FakeWindowHandle> clone(
1022 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001023 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001024 sp<FakeWindowHandle> handle =
1025 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1026 displayId, mInfo.token);
1027 return handle;
1028 }
1029
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001030 void setTouchable(bool touchable) {
1031 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1032 }
chaviwd1c23182019-12-20 18:44:56 -08001033
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001034 void setFocusable(bool focusable) {
1035 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1036 }
1037
1038 void setVisible(bool visible) {
1039 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1040 }
Vishnu Nair958da932020-08-21 17:12:37 -07001041
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001042 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001043 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001044 }
1045
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001046 void setPaused(bool paused) {
1047 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1048 }
1049
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001050 void setPreventSplitting(bool preventSplitting) {
1051 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001052 }
1053
1054 void setSlippery(bool slippery) {
1055 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1056 }
1057
1058 void setWatchOutsideTouch(bool watchOutside) {
1059 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1060 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001061
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001062 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1063
1064 void setInterceptsStylus(bool interceptsStylus) {
1065 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1066 }
1067
1068 void setDropInput(bool dropInput) {
1069 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1070 }
1071
1072 void setDropInputIfObscured(bool dropInputIfObscured) {
1073 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1074 }
1075
1076 void setNoInputChannel(bool noInputChannel) {
1077 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1078 }
1079
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001080 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1081
chaviw3277faf2021-05-19 16:45:23 -05001082 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001083
Bernardo Rufino7393d172021-02-26 13:56:11 +00001084 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1085
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001086 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001087 mInfo.frameLeft = frame.left;
1088 mInfo.frameTop = frame.top;
1089 mInfo.frameRight = frame.right;
1090 mInfo.frameBottom = frame.bottom;
1091 mInfo.touchableRegion.clear();
1092 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001093
1094 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1095 ui::Transform translate;
1096 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1097 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001098 }
1099
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001100 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1101
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001102 void setIsWallpaper(bool isWallpaper) {
1103 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1104 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001105
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001106 void setDupTouchToWallpaper(bool hasWallpaper) {
1107 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1108 }
chaviwd1c23182019-12-20 18:44:56 -08001109
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001110 void setTrustedOverlay(bool trustedOverlay) {
1111 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1112 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001113
chaviw9eaa22c2020-07-01 16:21:27 -07001114 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1115 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1116 }
1117
1118 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001119
yunho.shinf4a80b82020-11-16 21:13:57 +09001120 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1121
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001122 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1123 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1124 expectedFlags);
1125 }
1126
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001127 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1128 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1129 }
1130
Svet Ganov5d3bc372020-01-26 23:11:07 -08001131 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001132 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001133 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1134 expectedFlags);
1135 }
1136
1137 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001138 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001139 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1140 expectedFlags);
1141 }
1142
1143 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001145 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1146 }
1147
1148 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1149 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001150 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1151 expectedFlags);
1152 }
1153
Svet Ganov5d3bc372020-01-26 23:11:07 -08001154 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001155 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1156 int32_t expectedFlags = 0) {
1157 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1158 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001159 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1160 }
1161
1162 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001163 int32_t expectedFlags = 0) {
1164 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1165 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001166 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1167 }
1168
1169 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001170 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001171 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1172 expectedFlags);
1173 }
1174
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001175 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1176 int32_t expectedFlags = 0) {
1177 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1178 expectedFlags);
1179 }
1180
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001181 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1182 int32_t expectedFlags = 0) {
1183 InputEvent* event = consume();
1184 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1185 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1186 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1187 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1188 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1189 }
1190
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001191 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1192 ASSERT_NE(mInputReceiver, nullptr)
1193 << "Cannot consume events from a window with no receiver";
1194 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1195 }
1196
Prabir Pradhan99987712020-11-10 18:43:05 -08001197 void consumeCaptureEvent(bool hasCapture) {
1198 ASSERT_NE(mInputReceiver, nullptr)
1199 << "Cannot consume events from a window with no receiver";
1200 mInputReceiver->consumeCaptureEvent(hasCapture);
1201 }
1202
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001203 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1204 std::optional<int32_t> expectedDisplayId,
1205 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001206 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1207 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1208 expectedFlags);
1209 }
1210
arthurhungb89ccb02020-12-30 16:19:01 +08001211 void consumeDragEvent(bool isExiting, float x, float y) {
1212 mInputReceiver->consumeDragEvent(isExiting, x, y);
1213 }
1214
Antonio Kantekf16f2832021-09-28 04:39:20 +00001215 void consumeTouchModeEvent(bool inTouchMode) {
1216 ASSERT_NE(mInputReceiver, nullptr)
1217 << "Cannot consume events from a window with no receiver";
1218 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1219 }
1220
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001221 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001222 if (mInputReceiver == nullptr) {
1223 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1224 return std::nullopt;
1225 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001227 }
1228
1229 void finishEvent(uint32_t sequenceNum) {
1230 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1231 mInputReceiver->finishEvent(sequenceNum);
1232 }
1233
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001234 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1235 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1236 mInputReceiver->sendTimeline(inputEventId, timeline);
1237 }
1238
chaviwaf87b3e2019-10-01 16:59:28 -07001239 InputEvent* consume() {
1240 if (mInputReceiver == nullptr) {
1241 return nullptr;
1242 }
1243 return mInputReceiver->consume();
1244 }
1245
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001246 MotionEvent* consumeMotion() {
1247 InputEvent* event = consume();
1248 if (event == nullptr) {
1249 ADD_FAILURE() << "Consume failed : no event";
1250 return nullptr;
1251 }
1252 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1253 ADD_FAILURE() << "Instead of motion event, got "
1254 << inputEventTypeToString(event->getType());
1255 return nullptr;
1256 }
1257 return static_cast<MotionEvent*>(event);
1258 }
1259
Arthur Hungb92218b2018-08-14 12:00:21 +08001260 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001261 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001262 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001263 return; // Can't receive events if the window does not have input channel
1264 }
1265 ASSERT_NE(nullptr, mInputReceiver)
1266 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001267 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001268 }
1269
chaviwaf87b3e2019-10-01 16:59:28 -07001270 sp<IBinder> getToken() { return mInfo.token; }
1271
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001272 const std::string& getName() { return mName; }
1273
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001274 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1275 mInfo.ownerPid = ownerPid;
1276 mInfo.ownerUid = ownerUid;
1277 }
1278
Prabir Pradhanedd96402022-02-15 01:46:16 -08001279 int32_t getPid() const { return mInfo.ownerPid; }
1280
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001281 void destroyReceiver() { mInputReceiver = nullptr; }
1282
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001283 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1284
chaviwd1c23182019-12-20 18:44:56 -08001285private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001286 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001287 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001288 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001289};
1290
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001291std::atomic<int32_t> FakeWindowHandle::sId{1};
1292
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001293static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001294 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 int32_t displayId = ADISPLAY_ID_NONE,
1296 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001297 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001298 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1299 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001300 KeyEvent event;
1301 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1302
1303 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001304 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001305 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1306 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001307
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001308 if (!allowKeyRepeat) {
1309 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1310 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001311 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001312 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001313}
1314
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001315static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001317 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1318}
1319
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001320// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1321// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1322// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001323static InputEventInjectionResult injectKeyDownNoRepeat(
1324 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001325 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1326 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1327 /* allowKeyRepeat */ false);
1328}
1329
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001330static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001331 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001332 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1333}
1334
Garfield Tandf26e862020-07-01 20:18:19 -07001335class PointerBuilder {
1336public:
1337 PointerBuilder(int32_t id, int32_t toolType) {
1338 mProperties.clear();
1339 mProperties.id = id;
1340 mProperties.toolType = toolType;
1341 mCoords.clear();
1342 }
1343
1344 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1345
1346 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1347
1348 PointerBuilder& axis(int32_t axis, float value) {
1349 mCoords.setAxisValue(axis, value);
1350 return *this;
1351 }
1352
1353 PointerProperties buildProperties() const { return mProperties; }
1354
1355 PointerCoords buildCoords() const { return mCoords; }
1356
1357private:
1358 PointerProperties mProperties;
1359 PointerCoords mCoords;
1360};
1361
1362class MotionEventBuilder {
1363public:
1364 MotionEventBuilder(int32_t action, int32_t source) {
1365 mAction = action;
1366 mSource = source;
1367 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1368 }
1369
1370 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1371 mEventTime = eventTime;
1372 return *this;
1373 }
1374
1375 MotionEventBuilder& displayId(int32_t displayId) {
1376 mDisplayId = displayId;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& actionButton(int32_t actionButton) {
1381 mActionButton = actionButton;
1382 return *this;
1383 }
1384
arthurhung6d4bed92021-03-17 11:59:33 +08001385 MotionEventBuilder& buttonState(int32_t buttonState) {
1386 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001387 return *this;
1388 }
1389
1390 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1391 mRawXCursorPosition = rawXCursorPosition;
1392 return *this;
1393 }
1394
1395 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1396 mRawYCursorPosition = rawYCursorPosition;
1397 return *this;
1398 }
1399
1400 MotionEventBuilder& pointer(PointerBuilder pointer) {
1401 mPointers.push_back(pointer);
1402 return *this;
1403 }
1404
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001405 MotionEventBuilder& addFlag(uint32_t flags) {
1406 mFlags |= flags;
1407 return *this;
1408 }
1409
Garfield Tandf26e862020-07-01 20:18:19 -07001410 MotionEvent build() {
1411 std::vector<PointerProperties> pointerProperties;
1412 std::vector<PointerCoords> pointerCoords;
1413 for (const PointerBuilder& pointer : mPointers) {
1414 pointerProperties.push_back(pointer.buildProperties());
1415 pointerCoords.push_back(pointer.buildCoords());
1416 }
1417
1418 // Set mouse cursor position for the most common cases to avoid boilerplate.
1419 if (mSource == AINPUT_SOURCE_MOUSE &&
1420 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1421 mPointers.size() == 1) {
1422 mRawXCursorPosition = pointerCoords[0].getX();
1423 mRawYCursorPosition = pointerCoords[0].getY();
1424 }
1425
1426 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001427 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001428 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001429 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001430 mButtonState, MotionClassification::NONE, identityTransform,
1431 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001432 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1433 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001434
1435 return event;
1436 }
1437
1438private:
1439 int32_t mAction;
1440 int32_t mSource;
1441 nsecs_t mEventTime;
1442 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1443 int32_t mActionButton{0};
1444 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001445 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001446 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1447 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1448
1449 std::vector<PointerBuilder> mPointers;
1450};
1451
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001452static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001454 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001455 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1456 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1457 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1458 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001459}
1460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001462 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001463 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001464 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1466 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001468 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1469 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001470 MotionEvent event = MotionEventBuilder(action, source)
1471 .displayId(displayId)
1472 .eventTime(eventTime)
1473 .rawXCursorPosition(cursorPosition.x)
1474 .rawYCursorPosition(cursorPosition.y)
1475 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1476 .x(position.x)
1477 .y(position.y))
1478 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001479
1480 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001481 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1482 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001483}
1484
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001485static InputEventInjectionResult injectMotionDown(
1486 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1487 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001488 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001489}
1490
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001491static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 int32_t source, int32_t displayId,
1493 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001494 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001495}
1496
Jackal Guof9696682018-10-05 12:23:23 +08001497static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1498 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1499 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001500 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1501 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1502 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001503
1504 return args;
1505}
1506
chaviwd1c23182019-12-20 18:44:56 -08001507static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1508 const std::vector<PointF>& points) {
1509 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001510 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1511 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1512 }
1513
chaviwd1c23182019-12-20 18:44:56 -08001514 PointerProperties pointerProperties[pointerCount];
1515 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001516
chaviwd1c23182019-12-20 18:44:56 -08001517 for (size_t i = 0; i < pointerCount; i++) {
1518 pointerProperties[i].clear();
1519 pointerProperties[i].id = i;
1520 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001521
chaviwd1c23182019-12-20 18:44:56 -08001522 pointerCoords[i].clear();
1523 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1524 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1525 }
Jackal Guof9696682018-10-05 12:23:23 +08001526
1527 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1528 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001529 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001530 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1531 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001532 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1533 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001534 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1535 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001536
1537 return args;
1538}
1539
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001540static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1541 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1542}
1543
chaviwd1c23182019-12-20 18:44:56 -08001544static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1545 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1546}
1547
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001548static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1549 const PointerCaptureRequest& request) {
1550 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001551}
1552
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001553/**
1554 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1555 * broken channel.
1556 */
1557TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1558 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1559 sp<FakeWindowHandle> window =
1560 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1561 ADISPLAY_ID_DEFAULT);
1562
1563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1564
1565 // Window closes its channel, but the window remains.
1566 window->destroyReceiver();
1567 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1568}
1569
Arthur Hungb92218b2018-08-14 12:00:21 +08001570TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001572 sp<FakeWindowHandle> window =
1573 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001574
Arthur Hung72d8dc32020-03-28 00:48:39 +00001575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1577 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001579
1580 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001581 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001582}
1583
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001584TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1586 sp<FakeWindowHandle> window =
1587 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1588
1589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1590 // Inject a MotionEvent to an unknown display.
1591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1594
1595 // Window should receive motion event.
1596 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1597}
1598
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001599/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001600 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001601 * This test serves as a sanity check for the next test, where setInputWindows is
1602 * called twice.
1603 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001604TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606 sp<FakeWindowHandle> window =
1607 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1608 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001609
1610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1613 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 // Window should receive motion event.
1617 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1618}
1619
1620/**
1621 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001622 */
1623TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001624 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001625 sp<FakeWindowHandle> window =
1626 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1627 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001628
1629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001632 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1633 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001635
1636 // Window should receive motion event.
1637 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1638}
1639
Arthur Hungb92218b2018-08-14 12:00:21 +08001640// The foreground window should receive the first touch down event.
1641TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001642 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001643 sp<FakeWindowHandle> windowTop =
1644 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1645 sp<FakeWindowHandle> windowSecond =
1646 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001647
Arthur Hung72d8dc32020-03-28 00:48:39 +00001648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1650 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001652
1653 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001654 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001655 windowSecond->assertNoEvents();
1656}
1657
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001658/**
1659 * Two windows: A top window, and a wallpaper behind the window.
1660 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1661 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001662 * 1. foregroundWindow <-- dup touch to wallpaper
1663 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001664 */
1665TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1667 sp<FakeWindowHandle> foregroundWindow =
1668 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001669 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001670 sp<FakeWindowHandle> wallpaperWindow =
1671 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001672 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001673 constexpr int expectedWallpaperFlags =
1674 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1675
1676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1678 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1679 {100, 200}))
1680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1681
1682 // Both foreground window and its wallpaper should receive the touch down
1683 foregroundWindow->consumeMotionDown();
1684 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1685
1686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1687 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1688 ADISPLAY_ID_DEFAULT, {110, 200}))
1689 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1690
1691 foregroundWindow->consumeMotionMove();
1692 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1693
1694 // Now the foreground window goes away, but the wallpaper stays
1695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1696 foregroundWindow->consumeMotionCancel();
1697 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1698 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1699}
1700
1701/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001702 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1703 * with the following differences:
1704 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1705 * clean up the connection.
1706 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1707 * Ensure that there's no crash in the dispatcher.
1708 */
1709TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1710 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1711 sp<FakeWindowHandle> foregroundWindow =
1712 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001713 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001714 sp<FakeWindowHandle> wallpaperWindow =
1715 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001716 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001717 constexpr int expectedWallpaperFlags =
1718 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1719
1720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1722 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1723 {100, 200}))
1724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1725
1726 // Both foreground window and its wallpaper should receive the touch down
1727 foregroundWindow->consumeMotionDown();
1728 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1729
1730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1731 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1732 ADISPLAY_ID_DEFAULT, {110, 200}))
1733 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1734
1735 foregroundWindow->consumeMotionMove();
1736 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1737
1738 // Wallpaper closes its channel, but the window remains.
1739 wallpaperWindow->destroyReceiver();
1740 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1741
1742 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1743 // is no longer valid.
1744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1745 foregroundWindow->consumeMotionCancel();
1746}
1747
1748/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001749 * A single window that receives touch (on top), and a wallpaper window underneath it.
1750 * The top window gets a multitouch gesture.
1751 * Ensure that wallpaper gets the same gesture.
1752 */
1753TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1754 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1755 sp<FakeWindowHandle> window =
1756 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001757 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001758
1759 sp<FakeWindowHandle> wallpaperWindow =
1760 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001761 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001762 constexpr int expectedWallpaperFlags =
1763 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1764
1765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1766
1767 // Touch down on top window
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1770 {100, 100}))
1771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1772
1773 // Both top window and its wallpaper should receive the touch down
1774 window->consumeMotionDown();
1775 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1776
1777 // Second finger down on the top window
1778 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001779 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001780 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1781 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1782 .x(100)
1783 .y(100))
1784 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1785 .x(150)
1786 .y(150))
1787 .build();
1788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1789 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1790 InputEventInjectionSync::WAIT_FOR_RESULT))
1791 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1792
1793 window->consumeMotionPointerDown(1 /* pointerIndex */);
1794 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1795 expectedWallpaperFlags);
1796 window->assertNoEvents();
1797 wallpaperWindow->assertNoEvents();
1798}
1799
1800/**
1801 * Two windows: a window on the left and window on the right.
1802 * A third window, wallpaper, is behind both windows, and spans both top windows.
1803 * The first touch down goes to the left window. A second pointer touches down on the right window.
1804 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1805 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1806 * ACTION_POINTER_DOWN(1).
1807 */
1808TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1809 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1810 sp<FakeWindowHandle> leftWindow =
1811 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1812 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001813 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001814
1815 sp<FakeWindowHandle> rightWindow =
1816 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1817 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001818 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001819
1820 sp<FakeWindowHandle> wallpaperWindow =
1821 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1822 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001823 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001824 constexpr int expectedWallpaperFlags =
1825 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1826
1827 mDispatcher->setInputWindows(
1828 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1829
1830 // Touch down on left window
1831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1832 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1833 {100, 100}))
1834 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1835
1836 // Both foreground window and its wallpaper should receive the touch down
1837 leftWindow->consumeMotionDown();
1838 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1839
1840 // Second finger down on the right window
1841 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001842 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001843 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1844 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1845 .x(100)
1846 .y(100))
1847 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1848 .x(300)
1849 .y(100))
1850 .build();
1851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1852 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1853 InputEventInjectionSync::WAIT_FOR_RESULT))
1854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1855
1856 leftWindow->consumeMotionMove();
1857 // Since the touch is split, right window gets ACTION_DOWN
1858 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1859 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1860 expectedWallpaperFlags);
1861
1862 // Now, leftWindow, which received the first finger, disappears.
1863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1864 leftWindow->consumeMotionCancel();
1865 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1866 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1867
1868 // The pointer that's still down on the right window moves, and goes to the right window only.
1869 // As far as the dispatcher's concerned though, both pointers are still present.
1870 const MotionEvent secondFingerMoveEvent =
1871 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1872 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1873 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1874 .x(100)
1875 .y(100))
1876 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1877 .x(310)
1878 .y(110))
1879 .build();
1880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1881 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1882 InputEventInjectionSync::WAIT_FOR_RESULT));
1883 rightWindow->consumeMotionMove();
1884
1885 leftWindow->assertNoEvents();
1886 rightWindow->assertNoEvents();
1887 wallpaperWindow->assertNoEvents();
1888}
1889
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001890/**
1891 * On the display, have a single window, and also an area where there's no window.
1892 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1893 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1894 */
1895TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1897 sp<FakeWindowHandle> window =
1898 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1899
1900 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1901 NotifyMotionArgs args;
1902
1903 // Touch down on the empty space
1904 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1905
1906 mDispatcher->waitForIdle();
1907 window->assertNoEvents();
1908
1909 // Now touch down on the window with another pointer
1910 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1911 mDispatcher->waitForIdle();
1912 window->consumeMotionDown();
1913}
1914
1915/**
1916 * Same test as above, but instead of touching the empty space, the first touch goes to
1917 * non-touchable window.
1918 */
1919TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1920 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1921 sp<FakeWindowHandle> window1 =
1922 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1923 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1924 window1->setTouchable(false);
1925 sp<FakeWindowHandle> window2 =
1926 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1927 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1928
1929 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1930
1931 NotifyMotionArgs args;
1932 // Touch down on the non-touchable window
1933 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1934
1935 mDispatcher->waitForIdle();
1936 window1->assertNoEvents();
1937 window2->assertNoEvents();
1938
1939 // Now touch down on the window with another pointer
1940 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1941 mDispatcher->waitForIdle();
1942 window2->consumeMotionDown();
1943}
1944
Garfield Tandf26e862020-07-01 20:18:19 -07001945TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001947 sp<FakeWindowHandle> windowLeft =
1948 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1949 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001950 sp<FakeWindowHandle> windowRight =
1951 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1952 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001953
1954 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1955
1956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1957
1958 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001960 injectMotionEvent(mDispatcher,
1961 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1962 AINPUT_SOURCE_MOUSE)
1963 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1964 .x(900)
1965 .y(400))
1966 .build()));
1967 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1968 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1969 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1970 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1971
1972 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001974 injectMotionEvent(mDispatcher,
1975 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1976 AINPUT_SOURCE_MOUSE)
1977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1978 .x(300)
1979 .y(400))
1980 .build()));
1981 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1982 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1983 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1984 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1985 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1986 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1987
1988 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001990 injectMotionEvent(mDispatcher,
1991 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1992 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1993 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1994 .x(300)
1995 .y(400))
1996 .build()));
1997 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1998
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002000 injectMotionEvent(mDispatcher,
2001 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2002 AINPUT_SOURCE_MOUSE)
2003 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2004 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2005 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2006 .x(300)
2007 .y(400))
2008 .build()));
2009 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2010 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2011
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002013 injectMotionEvent(mDispatcher,
2014 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2015 AINPUT_SOURCE_MOUSE)
2016 .buttonState(0)
2017 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2018 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2019 .x(300)
2020 .y(400))
2021 .build()));
2022 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2023 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2024
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002026 injectMotionEvent(mDispatcher,
2027 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2028 .buttonState(0)
2029 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2030 .x(300)
2031 .y(400))
2032 .build()));
2033 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2034
2035 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002037 injectMotionEvent(mDispatcher,
2038 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2039 AINPUT_SOURCE_MOUSE)
2040 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2041 .x(900)
2042 .y(400))
2043 .build()));
2044 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2045 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2046 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2047 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2048 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2049 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2050}
2051
2052// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2053// directly in this test.
2054TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002055 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002056 sp<FakeWindowHandle> window =
2057 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2058 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002059
2060 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2061
2062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2063
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002065 injectMotionEvent(mDispatcher,
2066 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2067 AINPUT_SOURCE_MOUSE)
2068 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2069 .x(300)
2070 .y(400))
2071 .build()));
2072 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2073 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2074
2075 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002077 injectMotionEvent(mDispatcher,
2078 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2079 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2080 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2081 .x(300)
2082 .y(400))
2083 .build()));
2084 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2085
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002087 injectMotionEvent(mDispatcher,
2088 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2089 AINPUT_SOURCE_MOUSE)
2090 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2091 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2092 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2093 .x(300)
2094 .y(400))
2095 .build()));
2096 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2097 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2098
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002100 injectMotionEvent(mDispatcher,
2101 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2102 AINPUT_SOURCE_MOUSE)
2103 .buttonState(0)
2104 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2105 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2106 .x(300)
2107 .y(400))
2108 .build()));
2109 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2110 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2111
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002113 injectMotionEvent(mDispatcher,
2114 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2115 .buttonState(0)
2116 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2117 .x(300)
2118 .y(400))
2119 .build()));
2120 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2121
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002123 injectMotionEvent(mDispatcher,
2124 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2125 AINPUT_SOURCE_MOUSE)
2126 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2127 .x(300)
2128 .y(400))
2129 .build()));
2130 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2131 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2132}
2133
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02002134TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2135 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2136 sp<FakeWindowHandle> windowDefaultDisplay =
2137 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2138 ADISPLAY_ID_DEFAULT);
2139 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2140 sp<FakeWindowHandle> windowSecondDisplay =
2141 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2142 SECOND_DISPLAY_ID);
2143 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2144
2145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2146 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2147
2148 // Set cursor position in window in default display and check that hover enter and move
2149 // events are generated.
2150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2151 injectMotionEvent(mDispatcher,
2152 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2153 AINPUT_SOURCE_MOUSE)
2154 .displayId(ADISPLAY_ID_DEFAULT)
2155 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2156 .x(300)
2157 .y(600))
2158 .build()));
2159 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2160 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2161 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2162 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2163
2164 // Remove all windows in secondary display and check that no event happens on window in
2165 // primary display.
2166 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
2167 windowDefaultDisplay->assertNoEvents();
2168
2169 // Move cursor position in window in default display and check that only hover move
2170 // event is generated and not hover enter event.
2171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2172 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2174 injectMotionEvent(mDispatcher,
2175 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2176 AINPUT_SOURCE_MOUSE)
2177 .displayId(ADISPLAY_ID_DEFAULT)
2178 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2179 .x(400)
2180 .y(700))
2181 .build()));
2182 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2183 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2184 windowDefaultDisplay->assertNoEvents();
2185}
2186
Garfield Tan00f511d2019-06-12 16:55:40 -07002187TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002188 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002189
2190 sp<FakeWindowHandle> windowLeft =
2191 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2192 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002193 sp<FakeWindowHandle> windowRight =
2194 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2195 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002196
2197 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2198
Arthur Hung72d8dc32020-03-28 00:48:39 +00002199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002200
2201 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2202 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002204 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002205 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002206 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002207 windowRight->assertNoEvents();
2208}
2209
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002210TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002211 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002212 sp<FakeWindowHandle> window =
2213 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002214 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002215
Arthur Hung72d8dc32020-03-28 00:48:39 +00002216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002217 setFocusedWindow(window);
2218
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002219 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002220
2221 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2222 mDispatcher->notifyKey(&keyArgs);
2223
2224 // Window should receive key down event.
2225 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2226
2227 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2228 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002229 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002230 mDispatcher->notifyDeviceReset(&args);
2231 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2232 AKEY_EVENT_FLAG_CANCELED);
2233}
2234
2235TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002236 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002237 sp<FakeWindowHandle> window =
2238 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2239
Arthur Hung72d8dc32020-03-28 00:48:39 +00002240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002241
2242 NotifyMotionArgs motionArgs =
2243 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2244 ADISPLAY_ID_DEFAULT);
2245 mDispatcher->notifyMotion(&motionArgs);
2246
2247 // Window should receive motion down event.
2248 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2249
2250 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2251 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002252 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002253 mDispatcher->notifyDeviceReset(&args);
2254 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2255 0 /*expectedFlags*/);
2256}
2257
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002258TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2260 sp<FakeWindowHandle> window =
2261 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2262 window->setFocusable(true);
2263
2264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2265 setFocusedWindow(window);
2266
2267 window->consumeFocusEvent(true);
2268
2269 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2270 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2271 const nsecs_t injectTime = keyArgs.eventTime;
2272 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2273 mDispatcher->notifyKey(&keyArgs);
2274 // The dispatching time should be always greater than or equal to intercept key timeout.
2275 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2276 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2277 std::chrono::nanoseconds(interceptKeyTimeout).count());
2278}
2279
2280TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2282 sp<FakeWindowHandle> window =
2283 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2284 window->setFocusable(true);
2285
2286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2287 setFocusedWindow(window);
2288
2289 window->consumeFocusEvent(true);
2290
2291 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2292 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2293 mFakePolicy->setInterceptKeyTimeout(150ms);
2294 mDispatcher->notifyKey(&keyDown);
2295 mDispatcher->notifyKey(&keyUp);
2296
2297 // Window should receive key event immediately when same key up.
2298 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2299 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2300}
2301
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002302/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002303 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2304 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2305 * ACTION_OUTSIDE event is sent per gesture.
2306 */
2307TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2308 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2310 sp<FakeWindowHandle> window =
2311 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2312 window->setWatchOutsideTouch(true);
2313 window->setFrame(Rect{0, 0, 100, 100});
2314 sp<FakeWindowHandle> secondWindow =
2315 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2316 secondWindow->setFrame(Rect{100, 100, 200, 200});
2317 sp<FakeWindowHandle> thirdWindow =
2318 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2319 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2321
2322 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2323 NotifyMotionArgs motionArgs =
2324 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2325 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2326 mDispatcher->notifyMotion(&motionArgs);
2327 window->assertNoEvents();
2328 secondWindow->assertNoEvents();
2329
2330 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2331 // Now, `window` should get ACTION_OUTSIDE.
2332 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2333 {PointF{-10, -10}, PointF{105, 105}});
2334 mDispatcher->notifyMotion(&motionArgs);
2335 window->consumeMotionOutside();
2336 secondWindow->consumeMotionDown();
2337 thirdWindow->assertNoEvents();
2338
2339 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2340 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2341 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2342 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2343 mDispatcher->notifyMotion(&motionArgs);
2344 window->assertNoEvents();
2345 secondWindow->consumeMotionMove();
2346 thirdWindow->consumeMotionDown();
2347}
2348
Prabir Pradhan73fe4812022-07-22 20:22:18 +00002349TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2350 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2351 sp<FakeWindowHandle> window =
2352 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2353 window->setFocusable(true);
2354
2355 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2356 setFocusedWindow(window);
2357
2358 window->consumeFocusEvent(true);
2359
2360 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2361 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2362 mDispatcher->notifyKey(&keyDown);
2363 mDispatcher->notifyKey(&keyUp);
2364
2365 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2366 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2367
2368 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2369 mDispatcher->onWindowInfosChanged({}, {});
2370
2371 window->consumeFocusEvent(false);
2372
2373 mDispatcher->notifyKey(&keyDown);
2374 mDispatcher->notifyKey(&keyUp);
2375 window->assertNoEvents();
2376}
2377
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002378/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002379 * Ensure the correct coordinate spaces are used by InputDispatcher.
2380 *
2381 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2382 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2383 * space.
2384 */
2385class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2386public:
2387 void SetUp() override {
2388 InputDispatcherTest::SetUp();
2389 mDisplayInfos.clear();
2390 mWindowInfos.clear();
2391 }
2392
2393 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2394 gui::DisplayInfo info;
2395 info.displayId = displayId;
2396 info.transform = transform;
2397 mDisplayInfos.push_back(std::move(info));
2398 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2399 }
2400
2401 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2402 mWindowInfos.push_back(*windowHandle->getInfo());
2403 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2404 }
2405
2406 // Set up a test scenario where the display has a scaled projection and there are two windows
2407 // on the display.
2408 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2409 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2410 // respectively.
2411 ui::Transform displayTransform;
2412 displayTransform.set(2, 0, 0, 4);
2413 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2414
2415 std::shared_ptr<FakeApplicationHandle> application =
2416 std::make_shared<FakeApplicationHandle>();
2417
2418 // Add two windows to the display. Their frames are represented in the display space.
2419 sp<FakeWindowHandle> firstWindow =
2420 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002421 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2422 addWindow(firstWindow);
2423
2424 sp<FakeWindowHandle> secondWindow =
2425 new FakeWindowHandle(application, mDispatcher, "Second Window",
2426 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002427 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2428 addWindow(secondWindow);
2429 return {std::move(firstWindow), std::move(secondWindow)};
2430 }
2431
2432private:
2433 std::vector<gui::DisplayInfo> mDisplayInfos;
2434 std::vector<gui::WindowInfo> mWindowInfos;
2435};
2436
2437TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2438 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2439 // Send down to the first window. The point is represented in the display space. The point is
2440 // selected so that if the hit test was done with the transform applied to it, then it would
2441 // end up in the incorrect window.
2442 NotifyMotionArgs downMotionArgs =
2443 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2444 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2445 mDispatcher->notifyMotion(&downMotionArgs);
2446
2447 firstWindow->consumeMotionDown();
2448 secondWindow->assertNoEvents();
2449}
2450
2451// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2452// the event should be treated as being in the logical display space.
2453TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2454 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2455 // Send down to the first window. The point is represented in the logical display space. The
2456 // point is selected so that if the hit test was done in logical display space, then it would
2457 // end up in the incorrect window.
2458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2459 PointF{75 * 2, 55 * 4});
2460
2461 firstWindow->consumeMotionDown();
2462 secondWindow->assertNoEvents();
2463}
2464
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002465// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2466// event should be treated as being in the logical display space.
2467TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2468 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2469
2470 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2471 ui::Transform injectedEventTransform;
2472 injectedEventTransform.set(matrix);
2473 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2474 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2475
2476 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2477 .displayId(ADISPLAY_ID_DEFAULT)
2478 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2479 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2480 .x(untransformedPoint.x)
2481 .y(untransformedPoint.y))
2482 .build();
2483 event.transform(matrix);
2484
2485 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2486 InputEventInjectionSync::WAIT_FOR_RESULT);
2487
2488 firstWindow->consumeMotionDown();
2489 secondWindow->assertNoEvents();
2490}
2491
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002492TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2493 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2494
2495 // Send down to the second window.
2496 NotifyMotionArgs downMotionArgs =
2497 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2498 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2499 mDispatcher->notifyMotion(&downMotionArgs);
2500
2501 firstWindow->assertNoEvents();
2502 const MotionEvent* event = secondWindow->consumeMotion();
2503 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2504
2505 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2506 EXPECT_EQ(300, event->getRawX(0));
2507 EXPECT_EQ(880, event->getRawY(0));
2508
2509 // Ensure that the x and y values are in the window's coordinate space.
2510 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2511 // the logical display space. This will be the origin of the window space.
2512 EXPECT_EQ(100, event->getX(0));
2513 EXPECT_EQ(80, event->getY(0));
2514}
2515
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002516using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2517 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002518
2519class TransferTouchFixture : public InputDispatcherTest,
2520 public ::testing::WithParamInterface<TransferFunction> {};
2521
2522TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002523 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002524
2525 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002526 sp<FakeWindowHandle> firstWindow =
2527 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2528 sp<FakeWindowHandle> secondWindow =
2529 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002530
2531 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002533
2534 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002535 NotifyMotionArgs downMotionArgs =
2536 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2537 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002538 mDispatcher->notifyMotion(&downMotionArgs);
2539 // Only the first window should get the down event
2540 firstWindow->consumeMotionDown();
2541 secondWindow->assertNoEvents();
2542
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002543 // Transfer touch to the second window
2544 TransferFunction f = GetParam();
2545 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2546 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002547 // The first window gets cancel and the second gets down
2548 firstWindow->consumeMotionCancel();
2549 secondWindow->consumeMotionDown();
2550
2551 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002552 NotifyMotionArgs upMotionArgs =
2553 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2554 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002555 mDispatcher->notifyMotion(&upMotionArgs);
2556 // The first window gets no events and the second gets up
2557 firstWindow->assertNoEvents();
2558 secondWindow->consumeMotionUp();
2559}
2560
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002561/**
2562 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2563 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2564 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2565 * natural to the user.
2566 * In this test, we are sending a pointer to both spy window and first window. We then try to
2567 * transfer touch to the second window. The dispatcher should identify the first window as the
2568 * one that should lose the gesture, and therefore the action should be to move the gesture from
2569 * the first window to the second.
2570 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2571 * the other API, as well.
2572 */
2573TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2574 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2575
2576 // Create a couple of windows + a spy window
2577 sp<FakeWindowHandle> spyWindow =
2578 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2579 spyWindow->setTrustedOverlay(true);
2580 spyWindow->setSpy(true);
2581 sp<FakeWindowHandle> firstWindow =
2582 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2583 sp<FakeWindowHandle> secondWindow =
2584 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2585
2586 // Add the windows to the dispatcher
2587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2588
2589 // Send down to the first window
2590 NotifyMotionArgs downMotionArgs =
2591 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2592 ADISPLAY_ID_DEFAULT);
2593 mDispatcher->notifyMotion(&downMotionArgs);
2594 // Only the first window and spy should get the down event
2595 spyWindow->consumeMotionDown();
2596 firstWindow->consumeMotionDown();
2597
2598 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2599 // if f === 'transferTouch'.
2600 TransferFunction f = GetParam();
2601 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2602 ASSERT_TRUE(success);
2603 // The first window gets cancel and the second gets down
2604 firstWindow->consumeMotionCancel();
2605 secondWindow->consumeMotionDown();
2606
2607 // Send up event to the second window
2608 NotifyMotionArgs upMotionArgs =
2609 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2610 ADISPLAY_ID_DEFAULT);
2611 mDispatcher->notifyMotion(&upMotionArgs);
2612 // The first window gets no events and the second+spy get up
2613 firstWindow->assertNoEvents();
2614 spyWindow->consumeMotionUp();
2615 secondWindow->consumeMotionUp();
2616}
2617
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002618TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002620
2621 PointF touchPoint = {10, 10};
2622
2623 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002624 sp<FakeWindowHandle> firstWindow =
2625 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002626 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002627 sp<FakeWindowHandle> secondWindow =
2628 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002629 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002630
2631 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002633
2634 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002635 NotifyMotionArgs downMotionArgs =
2636 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2637 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002638 mDispatcher->notifyMotion(&downMotionArgs);
2639 // Only the first window should get the down event
2640 firstWindow->consumeMotionDown();
2641 secondWindow->assertNoEvents();
2642
2643 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002644 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002645 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002646 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002647 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2648 // Only the first window should get the pointer down event
2649 firstWindow->consumeMotionPointerDown(1);
2650 secondWindow->assertNoEvents();
2651
2652 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002653 TransferFunction f = GetParam();
2654 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2655 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002656 // The first window gets cancel and the second gets down and pointer down
2657 firstWindow->consumeMotionCancel();
2658 secondWindow->consumeMotionDown();
2659 secondWindow->consumeMotionPointerDown(1);
2660
2661 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002662 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002663 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002664 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002665 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2666 // The first window gets nothing and the second gets pointer up
2667 firstWindow->assertNoEvents();
2668 secondWindow->consumeMotionPointerUp(1);
2669
2670 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002671 NotifyMotionArgs upMotionArgs =
2672 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2673 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002674 mDispatcher->notifyMotion(&upMotionArgs);
2675 // The first window gets nothing and the second gets up
2676 firstWindow->assertNoEvents();
2677 secondWindow->consumeMotionUp();
2678}
2679
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002680// For the cases of single pointer touch and two pointers non-split touch, the api's
2681// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2682// for the case where there are multiple pointers split across several windows.
2683INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2684 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002685 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2686 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002687 return dispatcher->transferTouch(destChannelToken,
2688 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002689 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002690 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2691 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002692 return dispatcher->transferTouchFocus(from, to,
2693 false /*isDragAndDrop*/);
2694 }));
2695
Svet Ganov5d3bc372020-01-26 23:11:07 -08002696TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002697 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002698
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002699 sp<FakeWindowHandle> firstWindow =
2700 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002701 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002702
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002703 sp<FakeWindowHandle> secondWindow =
2704 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002705 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002706
2707 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002709
2710 PointF pointInFirst = {300, 200};
2711 PointF pointInSecond = {300, 600};
2712
2713 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002714 NotifyMotionArgs firstDownMotionArgs =
2715 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2716 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002717 mDispatcher->notifyMotion(&firstDownMotionArgs);
2718 // Only the first window should get the down event
2719 firstWindow->consumeMotionDown();
2720 secondWindow->assertNoEvents();
2721
2722 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002723 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002724 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002725 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002726 mDispatcher->notifyMotion(&secondDownMotionArgs);
2727 // The first window gets a move and the second a down
2728 firstWindow->consumeMotionMove();
2729 secondWindow->consumeMotionDown();
2730
2731 // Transfer touch focus to the second window
2732 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2733 // The first window gets cancel and the new gets pointer down (it already saw down)
2734 firstWindow->consumeMotionCancel();
2735 secondWindow->consumeMotionPointerDown(1);
2736
2737 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002738 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002739 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002740 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002741 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2742 // The first window gets nothing and the second gets pointer up
2743 firstWindow->assertNoEvents();
2744 secondWindow->consumeMotionPointerUp(1);
2745
2746 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002747 NotifyMotionArgs upMotionArgs =
2748 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2749 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002750 mDispatcher->notifyMotion(&upMotionArgs);
2751 // The first window gets nothing and the second gets up
2752 firstWindow->assertNoEvents();
2753 secondWindow->consumeMotionUp();
2754}
2755
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002756// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2757// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2758// touch is not supported, so the touch should continue on those windows and the transferred-to
2759// window should get nothing.
2760TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2762
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002763 sp<FakeWindowHandle> firstWindow =
2764 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2765 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002766
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002767 sp<FakeWindowHandle> secondWindow =
2768 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2769 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002770
2771 // Add the windows to the dispatcher
2772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2773
2774 PointF pointInFirst = {300, 200};
2775 PointF pointInSecond = {300, 600};
2776
2777 // Send down to the first window
2778 NotifyMotionArgs firstDownMotionArgs =
2779 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2780 ADISPLAY_ID_DEFAULT, {pointInFirst});
2781 mDispatcher->notifyMotion(&firstDownMotionArgs);
2782 // Only the first window should get the down event
2783 firstWindow->consumeMotionDown();
2784 secondWindow->assertNoEvents();
2785
2786 // Send down to the second window
2787 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002788 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002789 {pointInFirst, pointInSecond});
2790 mDispatcher->notifyMotion(&secondDownMotionArgs);
2791 // The first window gets a move and the second a down
2792 firstWindow->consumeMotionMove();
2793 secondWindow->consumeMotionDown();
2794
2795 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002796 const bool transferred =
2797 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002798 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2799 ASSERT_FALSE(transferred);
2800 firstWindow->assertNoEvents();
2801 secondWindow->assertNoEvents();
2802
2803 // The rest of the dispatch should proceed as normal
2804 // Send pointer up to the second window
2805 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002806 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002807 {pointInFirst, pointInSecond});
2808 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2809 // The first window gets MOVE and the second gets pointer up
2810 firstWindow->consumeMotionMove();
2811 secondWindow->consumeMotionUp();
2812
2813 // Send up event to the first window
2814 NotifyMotionArgs upMotionArgs =
2815 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2816 ADISPLAY_ID_DEFAULT);
2817 mDispatcher->notifyMotion(&upMotionArgs);
2818 // The first window gets nothing and the second gets up
2819 firstWindow->consumeMotionUp();
2820 secondWindow->assertNoEvents();
2821}
2822
Arthur Hungabbb9d82021-09-01 14:52:30 +00002823// This case will create two windows and one mirrored window on the default display and mirror
2824// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2825// the windows info of second display before default display.
2826TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2827 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2828 sp<FakeWindowHandle> firstWindowInPrimary =
2829 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2830 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002831 sp<FakeWindowHandle> secondWindowInPrimary =
2832 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2833 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002834
2835 sp<FakeWindowHandle> mirrorWindowInPrimary =
2836 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2837 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002838
2839 sp<FakeWindowHandle> firstWindowInSecondary =
2840 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2841 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002842
2843 sp<FakeWindowHandle> secondWindowInSecondary =
2844 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2845 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002846
2847 // Update window info, let it find window handle of second display first.
2848 mDispatcher->setInputWindows(
2849 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2850 {ADISPLAY_ID_DEFAULT,
2851 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2852
2853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2854 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2855 {50, 50}))
2856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2857
2858 // Window should receive motion event.
2859 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2860
2861 // Transfer touch focus
2862 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2863 secondWindowInPrimary->getToken()));
2864 // The first window gets cancel.
2865 firstWindowInPrimary->consumeMotionCancel();
2866 secondWindowInPrimary->consumeMotionDown();
2867
2868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2870 ADISPLAY_ID_DEFAULT, {150, 50}))
2871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2872 firstWindowInPrimary->assertNoEvents();
2873 secondWindowInPrimary->consumeMotionMove();
2874
2875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2876 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2877 {150, 50}))
2878 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2879 firstWindowInPrimary->assertNoEvents();
2880 secondWindowInPrimary->consumeMotionUp();
2881}
2882
2883// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2884// 'transferTouch' api.
2885TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2886 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2887 sp<FakeWindowHandle> firstWindowInPrimary =
2888 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2889 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002890 sp<FakeWindowHandle> secondWindowInPrimary =
2891 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2892 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002893
2894 sp<FakeWindowHandle> mirrorWindowInPrimary =
2895 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2896 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002897
2898 sp<FakeWindowHandle> firstWindowInSecondary =
2899 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2900 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002901
2902 sp<FakeWindowHandle> secondWindowInSecondary =
2903 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2904 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002905
2906 // Update window info, let it find window handle of second display first.
2907 mDispatcher->setInputWindows(
2908 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2909 {ADISPLAY_ID_DEFAULT,
2910 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2911
2912 // Touch on second display.
2913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2914 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2915 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2916
2917 // Window should receive motion event.
2918 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2919
2920 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002921 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002922
2923 // The first window gets cancel.
2924 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2925 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2926
2927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2928 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2929 SECOND_DISPLAY_ID, {150, 50}))
2930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2931 firstWindowInPrimary->assertNoEvents();
2932 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2933
2934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2935 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2936 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2937 firstWindowInPrimary->assertNoEvents();
2938 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2939}
2940
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002941TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002942 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002943 sp<FakeWindowHandle> window =
2944 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2945
Vishnu Nair47074b82020-08-14 11:54:47 -07002946 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002948 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002949
2950 window->consumeFocusEvent(true);
2951
2952 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2953 mDispatcher->notifyKey(&keyArgs);
2954
2955 // Window should receive key down event.
2956 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2957}
2958
2959TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002960 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002961 sp<FakeWindowHandle> window =
2962 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2963
Arthur Hung72d8dc32020-03-28 00:48:39 +00002964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002965
2966 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2967 mDispatcher->notifyKey(&keyArgs);
2968 mDispatcher->waitForIdle();
2969
2970 window->assertNoEvents();
2971}
2972
2973// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2974TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002975 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002976 sp<FakeWindowHandle> window =
2977 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2978
Arthur Hung72d8dc32020-03-28 00:48:39 +00002979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002980
2981 // Send key
2982 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2983 mDispatcher->notifyKey(&keyArgs);
2984 // Send motion
2985 NotifyMotionArgs motionArgs =
2986 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2987 ADISPLAY_ID_DEFAULT);
2988 mDispatcher->notifyMotion(&motionArgs);
2989
2990 // Window should receive only the motion event
2991 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2992 window->assertNoEvents(); // Key event or focus event will not be received
2993}
2994
arthurhungea3f4fc2020-12-21 23:18:53 +08002995TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2997
arthurhungea3f4fc2020-12-21 23:18:53 +08002998 sp<FakeWindowHandle> firstWindow =
2999 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3000 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003001
arthurhungea3f4fc2020-12-21 23:18:53 +08003002 sp<FakeWindowHandle> secondWindow =
3003 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3004 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003005
3006 // Add the windows to the dispatcher
3007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3008
3009 PointF pointInFirst = {300, 200};
3010 PointF pointInSecond = {300, 600};
3011
3012 // Send down to the first window
3013 NotifyMotionArgs firstDownMotionArgs =
3014 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3015 ADISPLAY_ID_DEFAULT, {pointInFirst});
3016 mDispatcher->notifyMotion(&firstDownMotionArgs);
3017 // Only the first window should get the down event
3018 firstWindow->consumeMotionDown();
3019 secondWindow->assertNoEvents();
3020
3021 // Send down to the second window
3022 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003023 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003024 {pointInFirst, pointInSecond});
3025 mDispatcher->notifyMotion(&secondDownMotionArgs);
3026 // The first window gets a move and the second a down
3027 firstWindow->consumeMotionMove();
3028 secondWindow->consumeMotionDown();
3029
3030 // Send pointer cancel to the second window
3031 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003032 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003033 {pointInFirst, pointInSecond});
3034 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3035 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3036 // The first window gets move and the second gets cancel.
3037 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3038 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3039
3040 // Send up event.
3041 NotifyMotionArgs upMotionArgs =
3042 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3043 ADISPLAY_ID_DEFAULT);
3044 mDispatcher->notifyMotion(&upMotionArgs);
3045 // The first window gets up and the second gets nothing.
3046 firstWindow->consumeMotionUp();
3047 secondWindow->assertNoEvents();
3048}
3049
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003050TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3051 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3052
3053 sp<FakeWindowHandle> window =
3054 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3056 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3057 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3058 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3059
3060 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3061 window->assertNoEvents();
3062 mDispatcher->waitForIdle();
3063}
3064
chaviwd1c23182019-12-20 18:44:56 -08003065class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003066public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003067 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003068 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003069 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003070 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003071 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003072 }
3073
chaviwd1c23182019-12-20 18:44:56 -08003074 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3075
3076 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3077 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3078 expectedDisplayId, expectedFlags);
3079 }
3080
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003081 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3082
3083 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3084
chaviwd1c23182019-12-20 18:44:56 -08003085 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3086 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3087 expectedDisplayId, expectedFlags);
3088 }
3089
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003090 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3091 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3092 expectedDisplayId, expectedFlags);
3093 }
3094
chaviwd1c23182019-12-20 18:44:56 -08003095 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3096 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3097 expectedDisplayId, expectedFlags);
3098 }
3099
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003100 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3101 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3102 expectedDisplayId, expectedFlags);
3103 }
3104
Arthur Hungfbfa5722021-11-16 02:45:54 +00003105 void consumeMotionPointerDown(int32_t pointerIdx) {
3106 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3107 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3108 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3109 0 /*expectedFlags*/);
3110 }
3111
Evan Rosky84f07f02021-04-16 10:42:42 -07003112 MotionEvent* consumeMotion() {
3113 InputEvent* event = mInputReceiver->consume();
3114 if (!event) {
3115 ADD_FAILURE() << "No event was produced";
3116 return nullptr;
3117 }
3118 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3119 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3120 return nullptr;
3121 }
3122 return static_cast<MotionEvent*>(event);
3123 }
3124
chaviwd1c23182019-12-20 18:44:56 -08003125 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3126
3127private:
3128 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003129};
3130
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003131using InputDispatcherMonitorTest = InputDispatcherTest;
3132
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003133/**
3134 * Two entities that receive touch: A window, and a global monitor.
3135 * The touch goes to the window, and then the window disappears.
3136 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3137 * for the monitor, as well.
3138 * 1. foregroundWindow
3139 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3140 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003141TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003142 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3143 sp<FakeWindowHandle> window =
3144 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3145
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003146 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003147
3148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3149 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3150 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3151 {100, 200}))
3152 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3153
3154 // Both the foreground window and the global monitor should receive the touch down
3155 window->consumeMotionDown();
3156 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3157
3158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3159 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3160 ADISPLAY_ID_DEFAULT, {110, 200}))
3161 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3162
3163 window->consumeMotionMove();
3164 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3165
3166 // Now the foreground window goes away
3167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3168 window->consumeMotionCancel();
3169 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3170
3171 // If more events come in, there will be no more foreground window to send them to. This will
3172 // cause a cancel for the monitor, as well.
3173 ASSERT_EQ(InputEventInjectionResult::FAILED,
3174 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3175 ADISPLAY_ID_DEFAULT, {120, 200}))
3176 << "Injection should fail because the window was removed";
3177 window->assertNoEvents();
3178 // Global monitor now gets the cancel
3179 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3180}
3181
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003182TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003183 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003184 sp<FakeWindowHandle> window =
3185 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003187
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003188 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003189
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003191 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003192 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003193 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003194 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003195}
3196
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003197TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3198 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003199
Chris Yea209fde2020-07-22 13:54:51 -07003200 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003201 sp<FakeWindowHandle> window =
3202 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003206 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003207 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003208 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003209 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003210
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003211 // Pilfer pointers from the monitor.
3212 // This should not do anything and the window should continue to receive events.
3213 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003214
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003216 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3217 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003218 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003219
3220 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3221 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003222}
3223
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003224TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3226 sp<FakeWindowHandle> window =
3227 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3229 window->setWindowOffset(20, 40);
3230 window->setWindowTransform(0, 1, -1, 0);
3231
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003232 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003233
3234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3235 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3236 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3237 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3238 MotionEvent* event = monitor.consumeMotion();
3239 // Even though window has transform, gesture monitor must not.
3240 ASSERT_EQ(ui::Transform(), event->getTransform());
3241}
3242
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003243TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003244 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003245 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003246
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003247 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003248 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003249 << "Injection should fail if there is a monitor, but no touchable window";
3250 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003251}
3252
chaviw81e2bb92019-12-18 15:03:51 -08003253TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003254 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003255 sp<FakeWindowHandle> window =
3256 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3257
Arthur Hung72d8dc32020-03-28 00:48:39 +00003258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003259
3260 NotifyMotionArgs motionArgs =
3261 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3262 ADISPLAY_ID_DEFAULT);
3263
3264 mDispatcher->notifyMotion(&motionArgs);
3265 // Window should receive motion down event.
3266 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3267
3268 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003269 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003270 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3271 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3272 motionArgs.pointerCoords[0].getX() - 10);
3273
3274 mDispatcher->notifyMotion(&motionArgs);
3275 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3276 0 /*expectedFlags*/);
3277}
3278
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003279/**
3280 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3281 * the device default right away. In the test scenario, we check both the default value,
3282 * and the action of enabling / disabling.
3283 */
3284TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003285 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003286 sp<FakeWindowHandle> window =
3287 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003288 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003289
3290 // Set focused application.
3291 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003292 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003293
3294 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003295 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003296 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003297 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3298
3299 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003300 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003302 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3303
3304 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003305 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3306 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003307 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003308 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003310 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003311 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3312
3313 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003314 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003316 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3317
3318 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003319 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3320 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003321 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003322 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003324 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003325 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3326
3327 window->assertNoEvents();
3328}
3329
Gang Wange9087892020-01-07 12:17:14 -05003330TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003331 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003332 sp<FakeWindowHandle> window =
3333 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3334
3335 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003336 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003337
Arthur Hung72d8dc32020-03-28 00:48:39 +00003338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003339 setFocusedWindow(window);
3340
Gang Wange9087892020-01-07 12:17:14 -05003341 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3342
3343 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3344 mDispatcher->notifyKey(&keyArgs);
3345
3346 InputEvent* event = window->consume();
3347 ASSERT_NE(event, nullptr);
3348
3349 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3350 ASSERT_NE(verified, nullptr);
3351 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3352
3353 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3354 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3355 ASSERT_EQ(keyArgs.source, verified->source);
3356 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3357
3358 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3359
3360 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003361 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003362 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003363 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3364 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3365 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3366 ASSERT_EQ(0, verifiedKey.repeatCount);
3367}
3368
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003369TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003371 sp<FakeWindowHandle> window =
3372 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3373
3374 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3375
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003376 ui::Transform transform;
3377 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3378
3379 gui::DisplayInfo displayInfo;
3380 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3381 displayInfo.transform = transform;
3382
3383 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003384
3385 NotifyMotionArgs motionArgs =
3386 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3387 ADISPLAY_ID_DEFAULT);
3388 mDispatcher->notifyMotion(&motionArgs);
3389
3390 InputEvent* event = window->consume();
3391 ASSERT_NE(event, nullptr);
3392
3393 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3394 ASSERT_NE(verified, nullptr);
3395 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3396
3397 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3398 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3399 EXPECT_EQ(motionArgs.source, verified->source);
3400 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3401
3402 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3403
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003404 const vec2 rawXY =
3405 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3406 motionArgs.pointerCoords[0].getXYValue());
3407 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3408 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003409 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003410 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003411 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003412 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3413 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3414}
3415
chaviw09c8d2d2020-08-24 15:48:26 -07003416/**
3417 * Ensure that separate calls to sign the same data are generating the same key.
3418 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3419 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3420 * tests.
3421 */
3422TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3423 KeyEvent event = getTestKeyEvent();
3424 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3425
3426 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3427 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3428 ASSERT_EQ(hmac1, hmac2);
3429}
3430
3431/**
3432 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3433 */
3434TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3435 KeyEvent event = getTestKeyEvent();
3436 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3437 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3438
3439 verifiedEvent.deviceId += 1;
3440 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3441
3442 verifiedEvent.source += 1;
3443 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3444
3445 verifiedEvent.eventTimeNanos += 1;
3446 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3447
3448 verifiedEvent.displayId += 1;
3449 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3450
3451 verifiedEvent.action += 1;
3452 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3453
3454 verifiedEvent.downTimeNanos += 1;
3455 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3456
3457 verifiedEvent.flags += 1;
3458 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3459
3460 verifiedEvent.keyCode += 1;
3461 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3462
3463 verifiedEvent.scanCode += 1;
3464 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3465
3466 verifiedEvent.metaState += 1;
3467 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3468
3469 verifiedEvent.repeatCount += 1;
3470 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3471}
3472
Vishnu Nair958da932020-08-21 17:12:37 -07003473TEST_F(InputDispatcherTest, SetFocusedWindow) {
3474 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3475 sp<FakeWindowHandle> windowTop =
3476 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3477 sp<FakeWindowHandle> windowSecond =
3478 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3479 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3480
3481 // Top window is also focusable but is not granted focus.
3482 windowTop->setFocusable(true);
3483 windowSecond->setFocusable(true);
3484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3485 setFocusedWindow(windowSecond);
3486
3487 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3489 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003490
3491 // Focused window should receive event.
3492 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3493 windowTop->assertNoEvents();
3494}
3495
3496TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3497 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3498 sp<FakeWindowHandle> window =
3499 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3500 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3501
3502 window->setFocusable(true);
3503 // Release channel for window is no longer valid.
3504 window->releaseChannel();
3505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3506 setFocusedWindow(window);
3507
3508 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003509 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3510 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003511
3512 // window channel is invalid, so it should not receive any input event.
3513 window->assertNoEvents();
3514}
3515
3516TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3517 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3518 sp<FakeWindowHandle> window =
3519 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003520 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003521 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3522
Vishnu Nair958da932020-08-21 17:12:37 -07003523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3524 setFocusedWindow(window);
3525
3526 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003527 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3528 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003529
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003530 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003531 window->assertNoEvents();
3532}
3533
3534TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3536 sp<FakeWindowHandle> windowTop =
3537 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3538 sp<FakeWindowHandle> windowSecond =
3539 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3540 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3541
3542 windowTop->setFocusable(true);
3543 windowSecond->setFocusable(true);
3544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3545 setFocusedWindow(windowTop);
3546 windowTop->consumeFocusEvent(true);
3547
3548 setFocusedWindow(windowSecond, windowTop);
3549 windowSecond->consumeFocusEvent(true);
3550 windowTop->consumeFocusEvent(false);
3551
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3553 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003554
3555 // Focused window should receive event.
3556 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3557}
3558
3559TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3561 sp<FakeWindowHandle> windowTop =
3562 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3563 sp<FakeWindowHandle> windowSecond =
3564 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3565 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3566
3567 windowTop->setFocusable(true);
3568 windowSecond->setFocusable(true);
3569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3570 setFocusedWindow(windowSecond, windowTop);
3571
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003572 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3573 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003574
3575 // Event should be dropped.
3576 windowTop->assertNoEvents();
3577 windowSecond->assertNoEvents();
3578}
3579
3580TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3581 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3582 sp<FakeWindowHandle> window =
3583 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3584 sp<FakeWindowHandle> previousFocusedWindow =
3585 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3586 ADISPLAY_ID_DEFAULT);
3587 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3588
3589 window->setFocusable(true);
3590 previousFocusedWindow->setFocusable(true);
3591 window->setVisible(false);
3592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3593 setFocusedWindow(previousFocusedWindow);
3594 previousFocusedWindow->consumeFocusEvent(true);
3595
3596 // Requesting focus on invisible window takes focus from currently focused window.
3597 setFocusedWindow(window);
3598 previousFocusedWindow->consumeFocusEvent(false);
3599
3600 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003602 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003603 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003604
3605 // Window does not get focus event or key down.
3606 window->assertNoEvents();
3607
3608 // Window becomes visible.
3609 window->setVisible(true);
3610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3611
3612 // Window receives focus event.
3613 window->consumeFocusEvent(true);
3614 // Focused window receives key down.
3615 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3616}
3617
Vishnu Nair599f1412021-06-21 10:39:58 -07003618TEST_F(InputDispatcherTest, DisplayRemoved) {
3619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3620 sp<FakeWindowHandle> window =
3621 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3622 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3623
3624 // window is granted focus.
3625 window->setFocusable(true);
3626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3627 setFocusedWindow(window);
3628 window->consumeFocusEvent(true);
3629
3630 // When a display is removed window loses focus.
3631 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3632 window->consumeFocusEvent(false);
3633}
3634
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003635/**
3636 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3637 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3638 * of the 'slipperyEnterWindow'.
3639 *
3640 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3641 * a way so that the touched location is no longer covered by the top window.
3642 *
3643 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3644 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3645 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3646 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3647 * with ACTION_DOWN).
3648 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3649 * window moved itself away from the touched location and had Flag::SLIPPERY.
3650 *
3651 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3652 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3653 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3654 *
3655 * In this test, we ensure that the event received by the bottom window has
3656 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3657 */
3658TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00003659 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3660 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003661
3662 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3663 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3664
3665 sp<FakeWindowHandle> slipperyExitWindow =
3666 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003667 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003668 // Make sure this one overlaps the bottom window
3669 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3670 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3671 // one. Windows with the same owner are not considered to be occluding each other.
3672 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3673
3674 sp<FakeWindowHandle> slipperyEnterWindow =
3675 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3676 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3677
3678 mDispatcher->setInputWindows(
3679 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3680
3681 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3682 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3683 ADISPLAY_ID_DEFAULT, {{50, 50}});
3684 mDispatcher->notifyMotion(&args);
3685 slipperyExitWindow->consumeMotionDown();
3686 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3687 mDispatcher->setInputWindows(
3688 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3689
3690 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3691 ADISPLAY_ID_DEFAULT, {{51, 51}});
3692 mDispatcher->notifyMotion(&args);
3693
3694 slipperyExitWindow->consumeMotionCancel();
3695
3696 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3697 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3698}
3699
Garfield Tan1c7bc862020-01-28 13:24:04 -08003700class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3701protected:
3702 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3703 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3704
Chris Yea209fde2020-07-22 13:54:51 -07003705 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003706 sp<FakeWindowHandle> mWindow;
3707
3708 virtual void SetUp() override {
3709 mFakePolicy = new FakeInputDispatcherPolicy();
3710 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003711 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003712 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3713 ASSERT_EQ(OK, mDispatcher->start());
3714
3715 setUpWindow();
3716 }
3717
3718 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003719 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003720 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3721
Vishnu Nair47074b82020-08-14 11:54:47 -07003722 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003724 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003725 mWindow->consumeFocusEvent(true);
3726 }
3727
Chris Ye2ad95392020-09-01 13:44:44 -07003728 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003729 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003730 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003731 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3732 mDispatcher->notifyKey(&keyArgs);
3733
3734 // Window should receive key down event.
3735 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3736 }
3737
3738 void expectKeyRepeatOnce(int32_t repeatCount) {
3739 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3740 InputEvent* repeatEvent = mWindow->consume();
3741 ASSERT_NE(nullptr, repeatEvent);
3742
3743 uint32_t eventType = repeatEvent->getType();
3744 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3745
3746 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3747 uint32_t eventAction = repeatKeyEvent->getAction();
3748 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3749 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3750 }
3751
Chris Ye2ad95392020-09-01 13:44:44 -07003752 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003753 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003754 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003755 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3756 mDispatcher->notifyKey(&keyArgs);
3757
3758 // Window should receive key down event.
3759 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3760 0 /*expectedFlags*/);
3761 }
3762};
3763
3764TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003765 sendAndConsumeKeyDown(1 /* deviceId */);
3766 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3767 expectKeyRepeatOnce(repeatCount);
3768 }
3769}
3770
3771TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3772 sendAndConsumeKeyDown(1 /* deviceId */);
3773 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3774 expectKeyRepeatOnce(repeatCount);
3775 }
3776 sendAndConsumeKeyDown(2 /* deviceId */);
3777 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003778 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3779 expectKeyRepeatOnce(repeatCount);
3780 }
3781}
3782
3783TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003784 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003785 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003786 sendAndConsumeKeyUp(1 /* deviceId */);
3787 mWindow->assertNoEvents();
3788}
3789
3790TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3791 sendAndConsumeKeyDown(1 /* deviceId */);
3792 expectKeyRepeatOnce(1 /*repeatCount*/);
3793 sendAndConsumeKeyDown(2 /* deviceId */);
3794 expectKeyRepeatOnce(1 /*repeatCount*/);
3795 // Stale key up from device 1.
3796 sendAndConsumeKeyUp(1 /* deviceId */);
3797 // Device 2 is still down, keep repeating
3798 expectKeyRepeatOnce(2 /*repeatCount*/);
3799 expectKeyRepeatOnce(3 /*repeatCount*/);
3800 // Device 2 key up
3801 sendAndConsumeKeyUp(2 /* deviceId */);
3802 mWindow->assertNoEvents();
3803}
3804
3805TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3806 sendAndConsumeKeyDown(1 /* deviceId */);
3807 expectKeyRepeatOnce(1 /*repeatCount*/);
3808 sendAndConsumeKeyDown(2 /* deviceId */);
3809 expectKeyRepeatOnce(1 /*repeatCount*/);
3810 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3811 sendAndConsumeKeyUp(2 /* deviceId */);
3812 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003813 mWindow->assertNoEvents();
3814}
3815
liushenxiang42232912021-05-21 20:24:09 +08003816TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3817 sendAndConsumeKeyDown(DEVICE_ID);
3818 expectKeyRepeatOnce(1 /*repeatCount*/);
3819 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3820 mDispatcher->notifyDeviceReset(&args);
3821 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3822 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3823 mWindow->assertNoEvents();
3824}
3825
Garfield Tan1c7bc862020-01-28 13:24:04 -08003826TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003827 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003828 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3829 InputEvent* repeatEvent = mWindow->consume();
3830 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3831 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3832 IdGenerator::getSource(repeatEvent->getId()));
3833 }
3834}
3835
3836TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003837 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003838
3839 std::unordered_set<int32_t> idSet;
3840 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3841 InputEvent* repeatEvent = mWindow->consume();
3842 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3843 int32_t id = repeatEvent->getId();
3844 EXPECT_EQ(idSet.end(), idSet.find(id));
3845 idSet.insert(id);
3846 }
3847}
3848
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003849/* Test InputDispatcher for MultiDisplay */
3850class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3851public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003852 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003853 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003854
Chris Yea209fde2020-07-22 13:54:51 -07003855 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003856 windowInPrimary =
3857 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003858
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003859 // Set focus window for primary display, but focused display would be second one.
3860 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003861 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003862 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003863 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003864 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003865
Chris Yea209fde2020-07-22 13:54:51 -07003866 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003867 windowInSecondary =
3868 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003869 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003870 // Set focus display to second one.
3871 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3872 // Set focus window for second display.
3873 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003874 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003875 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003876 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003877 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003878 }
3879
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003880 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003881 InputDispatcherTest::TearDown();
3882
Chris Yea209fde2020-07-22 13:54:51 -07003883 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003884 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003885 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003886 windowInSecondary.clear();
3887 }
3888
3889protected:
Chris Yea209fde2020-07-22 13:54:51 -07003890 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003891 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003892 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003893 sp<FakeWindowHandle> windowInSecondary;
3894};
3895
3896TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3897 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3899 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003901 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003902 windowInSecondary->assertNoEvents();
3903
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003904 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003908 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003909 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003910}
3911
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003912TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003913 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3915 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003916 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003917 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003918 windowInSecondary->assertNoEvents();
3919
3920 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003921 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003922 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003923 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003924 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003925
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003926 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003927 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003929 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003930 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3931 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003932
3933 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003934 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003935 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003936 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003937 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003938 windowInSecondary->assertNoEvents();
3939}
3940
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003941// Test per-display input monitors for motion event.
3942TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003943 FakeMonitorReceiver monitorInPrimary =
3944 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3945 FakeMonitorReceiver monitorInSecondary =
3946 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003947
3948 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3950 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3951 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003952 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003953 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003954 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003955 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003956
3957 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3960 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003961 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003962 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003963 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003964 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003965
3966 // Test inject a non-pointer motion event.
3967 // If specific a display, it will dispatch to the focused window of particular display,
3968 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003972 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003973 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003974 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003975 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003976}
3977
3978// Test per-display input monitors for key event.
3979TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003980 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003981 FakeMonitorReceiver monitorInPrimary =
3982 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3983 FakeMonitorReceiver monitorInSecondary =
3984 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003985
3986 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3988 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003989 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003990 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003991 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003992 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003993}
3994
Vishnu Nair958da932020-08-21 17:12:37 -07003995TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3996 sp<FakeWindowHandle> secondWindowInPrimary =
3997 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3998 secondWindowInPrimary->setFocusable(true);
3999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4000 setFocusedWindow(secondWindowInPrimary);
4001 windowInPrimary->consumeFocusEvent(false);
4002 secondWindowInPrimary->consumeFocusEvent(true);
4003
4004 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4006 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004007 windowInPrimary->assertNoEvents();
4008 windowInSecondary->assertNoEvents();
4009 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4010}
4011
Arthur Hungdfd528e2021-12-08 13:23:04 +00004012TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4013 FakeMonitorReceiver monitorInPrimary =
4014 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4015 FakeMonitorReceiver monitorInSecondary =
4016 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4017
4018 // Test touch down on primary display.
4019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4020 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4022 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4023 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4024
4025 // Test touch down on second display.
4026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4027 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4028 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4029 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4030 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4031
4032 // Trigger cancel touch.
4033 mDispatcher->cancelCurrentTouch();
4034 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4035 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4036 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4037 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4038
4039 // Test inject a move motion event, no window/monitor should receive the event.
4040 ASSERT_EQ(InputEventInjectionResult::FAILED,
4041 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4042 ADISPLAY_ID_DEFAULT, {110, 200}))
4043 << "Inject motion event should return InputEventInjectionResult::FAILED";
4044 windowInPrimary->assertNoEvents();
4045 monitorInPrimary.assertNoEvents();
4046
4047 ASSERT_EQ(InputEventInjectionResult::FAILED,
4048 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4049 SECOND_DISPLAY_ID, {110, 200}))
4050 << "Inject motion event should return InputEventInjectionResult::FAILED";
4051 windowInSecondary->assertNoEvents();
4052 monitorInSecondary.assertNoEvents();
4053}
4054
Jackal Guof9696682018-10-05 12:23:23 +08004055class InputFilterTest : public InputDispatcherTest {
4056protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004057 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4058 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004059 NotifyMotionArgs motionArgs;
4060
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004061 motionArgs =
4062 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004063 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004064 motionArgs =
4065 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004066 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004067 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004068 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004069 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4070 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004071 } else {
4072 mFakePolicy->assertFilterInputEventWasNotCalled();
4073 }
4074 }
4075
4076 void testNotifyKey(bool expectToBeFiltered) {
4077 NotifyKeyArgs keyArgs;
4078
4079 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4080 mDispatcher->notifyKey(&keyArgs);
4081 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4082 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004083 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004084
4085 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004086 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004087 } else {
4088 mFakePolicy->assertFilterInputEventWasNotCalled();
4089 }
4090 }
4091};
4092
4093// Test InputFilter for MotionEvent
4094TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4095 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4096 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4097 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4098
4099 // Enable InputFilter
4100 mDispatcher->setInputFilterEnabled(true);
4101 // Test touch on both primary and second display, and check if both events are filtered.
4102 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4103 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4104
4105 // Disable InputFilter
4106 mDispatcher->setInputFilterEnabled(false);
4107 // Test touch on both primary and second display, and check if both events aren't filtered.
4108 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4109 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4110}
4111
4112// Test InputFilter for KeyEvent
4113TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4114 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4115 testNotifyKey(/*expectToBeFiltered*/ false);
4116
4117 // Enable InputFilter
4118 mDispatcher->setInputFilterEnabled(true);
4119 // Send a key event, and check if it is filtered.
4120 testNotifyKey(/*expectToBeFiltered*/ true);
4121
4122 // Disable InputFilter
4123 mDispatcher->setInputFilterEnabled(false);
4124 // Send a key event, and check if it isn't filtered.
4125 testNotifyKey(/*expectToBeFiltered*/ false);
4126}
4127
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004128// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4129// logical display coordinate space.
4130TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4131 ui::Transform firstDisplayTransform;
4132 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4133 ui::Transform secondDisplayTransform;
4134 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4135
4136 std::vector<gui::DisplayInfo> displayInfos(2);
4137 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4138 displayInfos[0].transform = firstDisplayTransform;
4139 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4140 displayInfos[1].transform = secondDisplayTransform;
4141
4142 mDispatcher->onWindowInfosChanged({}, displayInfos);
4143
4144 // Enable InputFilter
4145 mDispatcher->setInputFilterEnabled(true);
4146
4147 // Ensure the correct transforms are used for the displays.
4148 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4149 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4150}
4151
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004152class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4153protected:
4154 virtual void SetUp() override {
4155 InputDispatcherTest::SetUp();
4156
4157 /**
4158 * We don't need to enable input filter to test the injected event policy, but we enabled it
4159 * here to make the tests more realistic, since this policy only matters when inputfilter is
4160 * on.
4161 */
4162 mDispatcher->setInputFilterEnabled(true);
4163
4164 std::shared_ptr<InputApplicationHandle> application =
4165 std::make_shared<FakeApplicationHandle>();
4166 mWindow =
4167 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4168
4169 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4170 mWindow->setFocusable(true);
4171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4172 setFocusedWindow(mWindow);
4173 mWindow->consumeFocusEvent(true);
4174 }
4175
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004176 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4177 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 KeyEvent event;
4179
4180 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4181 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4182 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4183 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4184 const int32_t additionalPolicyFlags =
4185 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004187 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004188 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4189 policyFlags | additionalPolicyFlags));
4190
4191 InputEvent* received = mWindow->consume();
4192 ASSERT_NE(nullptr, received);
4193 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004194 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4195 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4196 ASSERT_EQ(flags, keyEvent.getFlags());
4197 }
4198
4199 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4200 int32_t flags) {
4201 MotionEvent event;
4202 PointerProperties pointerProperties[1];
4203 PointerCoords pointerCoords[1];
4204 pointerProperties[0].clear();
4205 pointerProperties[0].id = 0;
4206 pointerCoords[0].clear();
4207 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4208 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4209
4210 ui::Transform identityTransform;
4211 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4212 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4213 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4214 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4215 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004216 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004217 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004218 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4219
4220 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004222 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4224 policyFlags | additionalPolicyFlags));
4225
4226 InputEvent* received = mWindow->consume();
4227 ASSERT_NE(nullptr, received);
4228 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4229 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4230 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4231 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004232 }
4233
4234private:
4235 sp<FakeWindowHandle> mWindow;
4236};
4237
4238TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004239 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4240 // filter. Without it, the event will no different from a regularly injected event, and the
4241 // injected device id will be overwritten.
4242 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4243 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004244}
4245
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004246TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004248 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4249 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4250}
4251
4252TEST_F(InputFilterInjectionPolicyTest,
4253 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4254 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4255 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4256 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004257}
4258
4259TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4260 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004261 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262}
4263
chaviwfd6d3512019-03-25 13:23:49 -07004264class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004265 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004266 InputDispatcherTest::SetUp();
4267
Chris Yea209fde2020-07-22 13:54:51 -07004268 std::shared_ptr<FakeApplicationHandle> application =
4269 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004270 mUnfocusedWindow =
4271 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004272 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004273
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004274 mFocusedWindow =
4275 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4276 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004277
4278 // Set focused application.
4279 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004280 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004281
4282 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004284 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004285 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004286 }
4287
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004288 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004289 InputDispatcherTest::TearDown();
4290
4291 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004292 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004293 }
4294
4295protected:
4296 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004297 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004298 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004299};
4300
4301// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4302// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4303// the onPointerDownOutsideFocus callback.
4304TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004306 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4307 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004309 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004310
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004311 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004312 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4313}
4314
4315// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4316// DOWN on the window that doesn't have focus. Ensure no window received the
4317// onPointerDownOutsideFocus callback.
4318TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004320 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004321 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004322 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004323
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004324 ASSERT_TRUE(mDispatcher->waitForIdle());
4325 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004326}
4327
4328// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4329// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4330TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4332 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004334 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004335
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004336 ASSERT_TRUE(mDispatcher->waitForIdle());
4337 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004338}
4339
4340// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4341// DOWN on the window that already has focus. Ensure no window received the
4342// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004343TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004345 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004346 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004347 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004348 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004349
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004350 ASSERT_TRUE(mDispatcher->waitForIdle());
4351 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004352}
4353
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004354// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4355// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4356TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4357 const MotionEvent event =
4358 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4359 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4360 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4361 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4362 .build();
4363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4364 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4365 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4366
4367 ASSERT_TRUE(mDispatcher->waitForIdle());
4368 mFakePolicy->assertOnPointerDownWasNotCalled();
4369 // Ensure that the unfocused window did not receive any FOCUS events.
4370 mUnfocusedWindow->assertNoEvents();
4371}
4372
chaviwaf87b3e2019-10-01 16:59:28 -07004373// These tests ensures we can send touch events to a single client when there are multiple input
4374// windows that point to the same client token.
4375class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4376 virtual void SetUp() override {
4377 InputDispatcherTest::SetUp();
4378
Chris Yea209fde2020-07-22 13:54:51 -07004379 std::shared_ptr<FakeApplicationHandle> application =
4380 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004381 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4382 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004383 mWindow1->setFrame(Rect(0, 0, 100, 100));
4384
4385 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4386 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004387 mWindow2->setFrame(Rect(100, 100, 200, 200));
4388
Arthur Hung72d8dc32020-03-28 00:48:39 +00004389 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004390 }
4391
4392protected:
4393 sp<FakeWindowHandle> mWindow1;
4394 sp<FakeWindowHandle> mWindow2;
4395
4396 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004397 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004398 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4399 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004400 }
4401
4402 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4403 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004404 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004405 InputEvent* event = window->consume();
4406
4407 ASSERT_NE(nullptr, event) << name.c_str()
4408 << ": consumer should have returned non-NULL event.";
4409
4410 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4411 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4412 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4413
4414 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004415 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004416
4417 for (size_t i = 0; i < points.size(); i++) {
4418 float expectedX = points[i].x;
4419 float expectedY = points[i].y;
4420
4421 EXPECT_EQ(expectedX, motionEvent.getX(i))
4422 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4423 << ", got " << motionEvent.getX(i);
4424 EXPECT_EQ(expectedY, motionEvent.getY(i))
4425 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4426 << ", got " << motionEvent.getY(i);
4427 }
4428 }
chaviw9eaa22c2020-07-01 16:21:27 -07004429
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004430 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004431 std::vector<PointF> expectedPoints) {
4432 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4433 ADISPLAY_ID_DEFAULT, touchedPoints);
4434 mDispatcher->notifyMotion(&motionArgs);
4435
4436 // Always consume from window1 since it's the window that has the InputReceiver
4437 consumeMotionEvent(mWindow1, action, expectedPoints);
4438 }
chaviwaf87b3e2019-10-01 16:59:28 -07004439};
4440
4441TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4442 // Touch Window 1
4443 PointF touchedPoint = {10, 10};
4444 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004445 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004446
4447 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004448 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004449
4450 // Touch Window 2
4451 touchedPoint = {150, 150};
4452 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004453 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004454}
4455
chaviw9eaa22c2020-07-01 16:21:27 -07004456TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4457 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004458 mWindow2->setWindowScale(0.5f, 0.5f);
4459
4460 // Touch Window 1
4461 PointF touchedPoint = {10, 10};
4462 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004463 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004464 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004465 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004466
4467 // Touch Window 2
4468 touchedPoint = {150, 150};
4469 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004470 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4471 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004472
chaviw9eaa22c2020-07-01 16:21:27 -07004473 // Update the transform so rotation is set
4474 mWindow2->setWindowTransform(0, -1, 1, 0);
4475 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4476 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004477}
4478
chaviw9eaa22c2020-07-01 16:21:27 -07004479TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004480 mWindow2->setWindowScale(0.5f, 0.5f);
4481
4482 // Touch Window 1
4483 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4484 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004485 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004486
4487 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004488 touchedPoints.push_back(PointF{150, 150});
4489 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004490 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004491
chaviw9eaa22c2020-07-01 16:21:27 -07004492 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004493 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004494 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004495
chaviw9eaa22c2020-07-01 16:21:27 -07004496 // Update the transform so rotation is set for Window 2
4497 mWindow2->setWindowTransform(0, -1, 1, 0);
4498 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004499 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004500}
4501
chaviw9eaa22c2020-07-01 16:21:27 -07004502TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004503 mWindow2->setWindowScale(0.5f, 0.5f);
4504
4505 // Touch Window 1
4506 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4507 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004508 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004509
4510 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004511 touchedPoints.push_back(PointF{150, 150});
4512 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004513
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004514 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004515
4516 // Move both windows
4517 touchedPoints = {{20, 20}, {175, 175}};
4518 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4519 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4520
chaviw9eaa22c2020-07-01 16:21:27 -07004521 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004522
chaviw9eaa22c2020-07-01 16:21:27 -07004523 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004524 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004525 expectedPoints.pop_back();
4526
4527 // Touch Window 2
4528 mWindow2->setWindowTransform(0, -1, 1, 0);
4529 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004530 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004531
4532 // Move both windows
4533 touchedPoints = {{20, 20}, {175, 175}};
4534 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4535 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4536
4537 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004538}
4539
4540TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4541 mWindow1->setWindowScale(0.5f, 0.5f);
4542
4543 // Touch Window 1
4544 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4545 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004546 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004547
4548 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004549 touchedPoints.push_back(PointF{150, 150});
4550 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004551
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004552 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004553
4554 // Move both windows
4555 touchedPoints = {{20, 20}, {175, 175}};
4556 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4557 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4558
chaviw9eaa22c2020-07-01 16:21:27 -07004559 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004560}
4561
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004562class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4563 virtual void SetUp() override {
4564 InputDispatcherTest::SetUp();
4565
Chris Yea209fde2020-07-22 13:54:51 -07004566 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004567 mApplication->setDispatchingTimeout(20ms);
4568 mWindow =
4569 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4570 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004571 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004572 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004573
4574 // Set focused application.
4575 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4576
4577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004578 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004579 mWindow->consumeFocusEvent(true);
4580 }
4581
4582 virtual void TearDown() override {
4583 InputDispatcherTest::TearDown();
4584 mWindow.clear();
4585 }
4586
4587protected:
Chris Yea209fde2020-07-22 13:54:51 -07004588 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004589 sp<FakeWindowHandle> mWindow;
4590 static constexpr PointF WINDOW_LOCATION = {20, 20};
4591
4592 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4595 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004597 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4598 WINDOW_LOCATION));
4599 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004600
4601 sp<FakeWindowHandle> addSpyWindow() {
4602 sp<FakeWindowHandle> spy =
4603 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4604 spy->setTrustedOverlay(true);
4605 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004606 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004607 spy->setDispatchingTimeout(30ms);
4608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4609 return spy;
4610 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004611};
4612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613// Send a tap and respond, which should not cause an ANR.
4614TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4615 tapOnWindow();
4616 mWindow->consumeMotionDown();
4617 mWindow->consumeMotionUp();
4618 ASSERT_TRUE(mDispatcher->waitForIdle());
4619 mFakePolicy->assertNotifyAnrWasNotCalled();
4620}
4621
4622// Send a regular key and respond, which should not cause an ANR.
4623TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4626 ASSERT_TRUE(mDispatcher->waitForIdle());
4627 mFakePolicy->assertNotifyAnrWasNotCalled();
4628}
4629
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004630TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4631 mWindow->setFocusable(false);
4632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4633 mWindow->consumeFocusEvent(false);
4634
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004635 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004636 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004637 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4638 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004640 // Key will not go to window because we have no focused window.
4641 // The 'no focused window' ANR timer should start instead.
4642
4643 // Now, the focused application goes away.
4644 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4645 // The key should get dropped and there should be no ANR.
4646
4647 ASSERT_TRUE(mDispatcher->waitForIdle());
4648 mFakePolicy->assertNotifyAnrWasNotCalled();
4649}
4650
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004651// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4653// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004654TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4657 WINDOW_LOCATION));
4658
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004659 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4660 ASSERT_TRUE(sequenceNum);
4661 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004662 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664 mWindow->finishEvent(*sequenceNum);
4665 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4666 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004667 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004668 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004669}
4670
4671// Send a key to the app and have the app not respond right away.
4672TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4673 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004675 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4676 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004677 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004678 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004679 ASSERT_TRUE(mDispatcher->waitForIdle());
4680}
4681
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682// We have a focused application, but no focused window
4683TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004684 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4686 mWindow->consumeFocusEvent(false);
4687
4688 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004690 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4691 WINDOW_LOCATION));
4692 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4693 mDispatcher->waitForIdle();
4694 mFakePolicy->assertNotifyAnrWasNotCalled();
4695
4696 // Once a focused event arrives, we get an ANR for this application
4697 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4698 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004701 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004704 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705 ASSERT_TRUE(mDispatcher->waitForIdle());
4706}
4707
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004708/**
4709 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4710 * there will not be an ANR.
4711 */
4712TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4713 mWindow->setFocusable(false);
4714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4715 mWindow->consumeFocusEvent(false);
4716
4717 KeyEvent event;
4718 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4719 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4720
4721 // Define a valid key down event that is stale (too old).
4722 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4723 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4724 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4725
4726 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4727
4728 InputEventInjectionResult result =
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004729 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004730 InputEventInjectionSync::WAIT_FOR_RESULT,
4731 INJECT_EVENT_TIMEOUT, policyFlags);
4732 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4733 << "Injection should fail because the event is stale";
4734
4735 ASSERT_TRUE(mDispatcher->waitForIdle());
4736 mFakePolicy->assertNotifyAnrWasNotCalled();
4737 mWindow->assertNoEvents();
4738}
4739
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004741// Make sure that we don't notify policy twice about the same ANR.
4742TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004743 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4745 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746
4747 // Once a focused event arrives, we get an ANR for this application
4748 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4749 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004750 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004751 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004752 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 const std::chrono::duration appTimeout =
4755 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004756 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004758 std::this_thread::sleep_for(appTimeout);
4759 // ANR should not be raised again. It is up to policy to do that if it desires.
4760 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004762 // If we now get a focused window, the ANR should stop, but the policy handles that via
4763 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764 ASSERT_TRUE(mDispatcher->waitForIdle());
4765}
4766
4767// We have a focused application, but no focused window
4768TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004769 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4771 mWindow->consumeFocusEvent(false);
4772
4773 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004774 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004775 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4777 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778
4779 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004780 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781
4782 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004783 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 ASSERT_TRUE(mDispatcher->waitForIdle());
4785 mWindow->assertNoEvents();
4786}
4787
4788/**
4789 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4790 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4791 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4792 * the ANR mechanism should still work.
4793 *
4794 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4795 * DOWN event, while not responding on the second one.
4796 */
4797TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4798 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4799 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4800 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4801 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4802 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004803 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804
4805 // Now send ACTION_UP, with identical timestamp
4806 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4807 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4808 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4809 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811
4812 // We have now sent down and up. Let's consume first event and then ANR on the second.
4813 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4814 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004815 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004816}
4817
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004818// A spy window can receive an ANR
4819TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4820 sp<FakeWindowHandle> spy = addSpyWindow();
4821
4822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4823 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4824 WINDOW_LOCATION));
4825 mWindow->consumeMotionDown();
4826
4827 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4828 ASSERT_TRUE(sequenceNum);
4829 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004830 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004831
4832 spy->finishEvent(*sequenceNum);
4833 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4834 0 /*flags*/);
4835 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004836 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004837}
4838
4839// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004841TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4842 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4845 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848
4849 // Stuck on the ACTION_UP
4850 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004851 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004853 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004854 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4856 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857
4858 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4859 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004860 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004862 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863}
4864
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004865// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004867TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4868 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004869
4870 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004871 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4872 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873
4874 mWindow->consumeMotionDown();
4875 // Stuck on the ACTION_UP
4876 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004877 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004879 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004880 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004881 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4882 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883
4884 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4885 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004886 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004888 spy->assertNoEvents();
4889}
4890
4891TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4892 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4893
4894 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4895
4896 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4897 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4898 WINDOW_LOCATION));
4899
4900 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4901 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4902 ASSERT_TRUE(consumeSeq);
4903
Prabir Pradhanedd96402022-02-15 01:46:16 -08004904 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004905
4906 monitor.finishEvent(*consumeSeq);
4907 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4908
4909 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004910 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911}
4912
4913// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4914// process events, you don't get an anr. When the window later becomes unresponsive again, you
4915// get an ANR again.
4916// 1. tap -> block on ACTION_UP -> receive ANR
4917// 2. consume all pending events (= queue becomes healthy again)
4918// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4919TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4920 tapOnWindow();
4921
4922 mWindow->consumeMotionDown();
4923 // Block on ACTION_UP
4924 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004925 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4927 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004928 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929 mWindow->assertNoEvents();
4930
4931 tapOnWindow();
4932 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004933 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 mWindow->consumeMotionUp();
4935
4936 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004937 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004938 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004939 mWindow->assertNoEvents();
4940}
4941
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004942// If a connection remains unresponsive for a while, make sure policy is only notified once about
4943// it.
4944TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4947 WINDOW_LOCATION));
4948
4949 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004950 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004952 // 'notifyConnectionUnresponsive' should only be called once per connection
4953 mFakePolicy->assertNotifyAnrWasNotCalled();
4954 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004955 mWindow->consumeMotionDown();
4956 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4957 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4958 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004959 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004960 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004961 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962}
4963
4964/**
4965 * If a window is processing a motion event, and then a key event comes in, the key event should
4966 * not to to the focused window until the motion is processed.
4967 *
4968 * Warning!!!
4969 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4970 * and the injection timeout that we specify when injecting the key.
4971 * We must have the injection timeout (10ms) be smaller than
4972 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4973 *
4974 * If that value changes, this test should also change.
4975 */
4976TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4977 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4978 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4979
4980 tapOnWindow();
4981 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4982 ASSERT_TRUE(downSequenceNum);
4983 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4984 ASSERT_TRUE(upSequenceNum);
4985 // Don't finish the events yet, and send a key
4986 // Injection will "succeed" because we will eventually give up and send the key to the focused
4987 // window even if motions are still being processed. But because the injection timeout is short,
4988 // we will receive INJECTION_TIMED_OUT as the result.
4989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004990 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004992 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4993 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004994 // Key will not be sent to the window, yet, because the window is still processing events
4995 // and the key remains pending, waiting for the touch events to be processed
4996 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4997 ASSERT_FALSE(keySequenceNum);
4998
4999 std::this_thread::sleep_for(500ms);
5000 // if we wait long enough though, dispatcher will give up, and still send the key
5001 // to the focused window, even though we have not yet finished the motion event
5002 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5003 mWindow->finishEvent(*downSequenceNum);
5004 mWindow->finishEvent(*upSequenceNum);
5005}
5006
5007/**
5008 * If a window is processing a motion event, and then a key event comes in, the key event should
5009 * not go to the focused window until the motion is processed.
5010 * If then a new motion comes in, then the pending key event should be going to the currently
5011 * focused window right away.
5012 */
5013TEST_F(InputDispatcherSingleWindowAnr,
5014 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5015 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5016 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5017
5018 tapOnWindow();
5019 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5020 ASSERT_TRUE(downSequenceNum);
5021 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5022 ASSERT_TRUE(upSequenceNum);
5023 // Don't finish the events yet, and send a key
5024 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005026 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005027 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028 // At this point, key is still pending, and should not be sent to the application yet.
5029 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5030 ASSERT_FALSE(keySequenceNum);
5031
5032 // Now tap down again. It should cause the pending key to go to the focused window right away.
5033 tapOnWindow();
5034 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5035 // the other events yet. We can finish events in any order.
5036 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5037 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5038 mWindow->consumeMotionDown();
5039 mWindow->consumeMotionUp();
5040 mWindow->assertNoEvents();
5041}
5042
5043class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5044 virtual void SetUp() override {
5045 InputDispatcherTest::SetUp();
5046
Chris Yea209fde2020-07-22 13:54:51 -07005047 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048 mApplication->setDispatchingTimeout(10ms);
5049 mUnfocusedWindow =
5050 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5051 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005052 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005053 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054
5055 mFocusedWindow =
5056 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005057 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005058 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005059
5060 // Set focused application.
5061 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005062 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005063
5064 // Expect one focus window exist in display.
5065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005066 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067 mFocusedWindow->consumeFocusEvent(true);
5068 }
5069
5070 virtual void TearDown() override {
5071 InputDispatcherTest::TearDown();
5072
5073 mUnfocusedWindow.clear();
5074 mFocusedWindow.clear();
5075 }
5076
5077protected:
Chris Yea209fde2020-07-22 13:54:51 -07005078 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005079 sp<FakeWindowHandle> mUnfocusedWindow;
5080 sp<FakeWindowHandle> mFocusedWindow;
5081 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5082 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5083 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5084
5085 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5086
5087 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5088
5089private:
5090 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005092 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5093 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005095 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5096 location));
5097 }
5098};
5099
5100// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5101// should be ANR'd first.
5102TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005104 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5105 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005106 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005107 mFocusedWindow->consumeMotionDown();
5108 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5109 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5110 // We consumed all events, so no ANR
5111 ASSERT_TRUE(mDispatcher->waitForIdle());
5112 mFakePolicy->assertNotifyAnrWasNotCalled();
5113
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5116 FOCUSED_WINDOW_LOCATION));
5117 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5118 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005119
5120 const std::chrono::duration timeout =
5121 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005122 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005123 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5124 // sequence to make it consistent
5125 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005126 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005127 mFocusedWindow->consumeMotionDown();
5128 // This cancel is generated because the connection was unresponsive
5129 mFocusedWindow->consumeMotionCancel();
5130 mFocusedWindow->assertNoEvents();
5131 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005133 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5134 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005135 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136}
5137
5138// If we have 2 windows with identical timeouts that are both unresponsive,
5139// it doesn't matter which order they should have ANR.
5140// But we should receive ANR for both.
5141TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5142 // Set the timeout for unfocused window to match the focused window
5143 mUnfocusedWindow->setDispatchingTimeout(10ms);
5144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5145
5146 tapOnFocusedWindow();
5147 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005148 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5149 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5150 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005151
5152 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005153 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5154 mFocusedWindow->getToken() == anrConnectionToken2);
5155 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5156 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005157
5158 ASSERT_TRUE(mDispatcher->waitForIdle());
5159 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005160
5161 mFocusedWindow->consumeMotionDown();
5162 mFocusedWindow->consumeMotionUp();
5163 mUnfocusedWindow->consumeMotionOutside();
5164
Prabir Pradhanedd96402022-02-15 01:46:16 -08005165 sp<IBinder> responsiveToken1, responsiveToken2;
5166 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5167 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005168
5169 // Both applications should be marked as responsive, in any order
5170 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5171 mFocusedWindow->getToken() == responsiveToken2);
5172 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5173 mUnfocusedWindow->getToken() == responsiveToken2);
5174 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005175}
5176
5177// If a window is already not responding, the second tap on the same window should be ignored.
5178// We should also log an error to account for the dropped event (not tested here).
5179// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5180TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5181 tapOnFocusedWindow();
5182 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5183 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5184 // Receive the events, but don't respond
5185 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5186 ASSERT_TRUE(downEventSequenceNum);
5187 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5188 ASSERT_TRUE(upEventSequenceNum);
5189 const std::chrono::duration timeout =
5190 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005191 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005192
5193 // Tap once again
5194 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005195 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5197 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005198 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5200 FOCUSED_WINDOW_LOCATION));
5201 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5202 // valid touch target
5203 mUnfocusedWindow->assertNoEvents();
5204
5205 // Consume the first tap
5206 mFocusedWindow->finishEvent(*downEventSequenceNum);
5207 mFocusedWindow->finishEvent(*upEventSequenceNum);
5208 ASSERT_TRUE(mDispatcher->waitForIdle());
5209 // The second tap did not go to the focused window
5210 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005211 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005212 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5213 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005214 mFakePolicy->assertNotifyAnrWasNotCalled();
5215}
5216
5217// If you tap outside of all windows, there will not be ANR
5218TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005219 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5221 LOCATION_OUTSIDE_ALL_WINDOWS));
5222 ASSERT_TRUE(mDispatcher->waitForIdle());
5223 mFakePolicy->assertNotifyAnrWasNotCalled();
5224}
5225
5226// Since the focused window is paused, tapping on it should not produce any events
5227TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5228 mFocusedWindow->setPaused(true);
5229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5230
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005231 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005232 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5233 FOCUSED_WINDOW_LOCATION));
5234
5235 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5236 ASSERT_TRUE(mDispatcher->waitForIdle());
5237 // Should not ANR because the window is paused, and touches shouldn't go to it
5238 mFakePolicy->assertNotifyAnrWasNotCalled();
5239
5240 mFocusedWindow->assertNoEvents();
5241 mUnfocusedWindow->assertNoEvents();
5242}
5243
5244/**
5245 * If a window is processing a motion event, and then a key event comes in, the key event should
5246 * not to to the focused window until the motion is processed.
5247 * If a different window becomes focused at this time, the key should go to that window instead.
5248 *
5249 * Warning!!!
5250 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5251 * and the injection timeout that we specify when injecting the key.
5252 * We must have the injection timeout (10ms) be smaller than
5253 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5254 *
5255 * If that value changes, this test should also change.
5256 */
5257TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5258 // Set a long ANR timeout to prevent it from triggering
5259 mFocusedWindow->setDispatchingTimeout(2s);
5260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5261
5262 tapOnUnfocusedWindow();
5263 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5264 ASSERT_TRUE(downSequenceNum);
5265 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5266 ASSERT_TRUE(upSequenceNum);
5267 // Don't finish the events yet, and send a key
5268 // Injection will succeed because we will eventually give up and send the key to the focused
5269 // window even if motions are still being processed.
5270
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005271 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005272 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005273 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005275 // Key will not be sent to the window, yet, because the window is still processing events
5276 // and the key remains pending, waiting for the touch events to be processed
5277 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5278 ASSERT_FALSE(keySequenceNum);
5279
5280 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005281 mFocusedWindow->setFocusable(false);
5282 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005284 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005285
5286 // Focus events should precede the key events
5287 mUnfocusedWindow->consumeFocusEvent(true);
5288 mFocusedWindow->consumeFocusEvent(false);
5289
5290 // Finish the tap events, which should unblock dispatcher
5291 mUnfocusedWindow->finishEvent(*downSequenceNum);
5292 mUnfocusedWindow->finishEvent(*upSequenceNum);
5293
5294 // Now that all queues are cleared and no backlog in the connections, the key event
5295 // can finally go to the newly focused "mUnfocusedWindow".
5296 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5297 mFocusedWindow->assertNoEvents();
5298 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005299 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005300}
5301
5302// When the touch stream is split across 2 windows, and one of them does not respond,
5303// then ANR should be raised and the touch should be canceled for the unresponsive window.
5304// The other window should not be affected by that.
5305TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5306 // Touch Window 1
5307 NotifyMotionArgs motionArgs =
5308 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5309 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5310 mDispatcher->notifyMotion(&motionArgs);
5311 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5312 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5313
5314 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005315 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5316 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317 mDispatcher->notifyMotion(&motionArgs);
5318
5319 const std::chrono::duration timeout =
5320 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005321 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005322
5323 mUnfocusedWindow->consumeMotionDown();
5324 mFocusedWindow->consumeMotionDown();
5325 // Focused window may or may not receive ACTION_MOVE
5326 // But it should definitely receive ACTION_CANCEL due to the ANR
5327 InputEvent* event;
5328 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5329 ASSERT_TRUE(moveOrCancelSequenceNum);
5330 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5331 ASSERT_NE(nullptr, event);
5332 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5333 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5334 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5335 mFocusedWindow->consumeMotionCancel();
5336 } else {
5337 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5338 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005339 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005340 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5341 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005342
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005343 mUnfocusedWindow->assertNoEvents();
5344 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005345 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005346}
5347
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005348/**
5349 * If we have no focused window, and a key comes in, we start the ANR timer.
5350 * The focused application should add a focused window before the timer runs out to prevent ANR.
5351 *
5352 * If the user touches another application during this time, the key should be dropped.
5353 * Next, if a new focused window comes in, without toggling the focused application,
5354 * then no ANR should occur.
5355 *
5356 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5357 * but in some cases the policy may not update the focused application.
5358 */
5359TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5360 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5361 std::make_shared<FakeApplicationHandle>();
5362 focusedApplication->setDispatchingTimeout(60ms);
5363 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5364 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5365 mFocusedWindow->setFocusable(false);
5366
5367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5368 mFocusedWindow->consumeFocusEvent(false);
5369
5370 // Send a key. The ANR timer should start because there is no focused window.
5371 // 'focusedApplication' will get blamed if this timer completes.
5372 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005373 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005374 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005375 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5376 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005378
5379 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5380 // then the injected touches won't cause the focused event to get dropped.
5381 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5382 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5383 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5384 // For this test, it means that the key would get delivered to the window once it becomes
5385 // focused.
5386 std::this_thread::sleep_for(10ms);
5387
5388 // Touch unfocused window. This should force the pending key to get dropped.
5389 NotifyMotionArgs motionArgs =
5390 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5391 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5392 mDispatcher->notifyMotion(&motionArgs);
5393
5394 // We do not consume the motion right away, because that would require dispatcher to first
5395 // process (== drop) the key event, and by that time, ANR will be raised.
5396 // Set the focused window first.
5397 mFocusedWindow->setFocusable(true);
5398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5399 setFocusedWindow(mFocusedWindow);
5400 mFocusedWindow->consumeFocusEvent(true);
5401 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5402 // to another application. This could be a bug / behaviour in the policy.
5403
5404 mUnfocusedWindow->consumeMotionDown();
5405
5406 ASSERT_TRUE(mDispatcher->waitForIdle());
5407 // Should not ANR because we actually have a focused window. It was just added too slowly.
5408 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5409}
5410
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005411// These tests ensure we cannot send touch events to a window that's positioned behind a window
5412// that has feature NO_INPUT_CHANNEL.
5413// Layout:
5414// Top (closest to user)
5415// mNoInputWindow (above all windows)
5416// mBottomWindow
5417// Bottom (furthest from user)
5418class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5419 virtual void SetUp() override {
5420 InputDispatcherTest::SetUp();
5421
5422 mApplication = std::make_shared<FakeApplicationHandle>();
5423 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5424 "Window without input channel", ADISPLAY_ID_DEFAULT,
5425 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5426
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005427 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005428 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5429 // It's perfectly valid for this window to not have an associated input channel
5430
5431 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5432 ADISPLAY_ID_DEFAULT);
5433 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5434
5435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5436 }
5437
5438protected:
5439 std::shared_ptr<FakeApplicationHandle> mApplication;
5440 sp<FakeWindowHandle> mNoInputWindow;
5441 sp<FakeWindowHandle> mBottomWindow;
5442};
5443
5444TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5445 PointF touchedPoint = {10, 10};
5446
5447 NotifyMotionArgs motionArgs =
5448 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5449 ADISPLAY_ID_DEFAULT, {touchedPoint});
5450 mDispatcher->notifyMotion(&motionArgs);
5451
5452 mNoInputWindow->assertNoEvents();
5453 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5454 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5455 // and therefore should prevent mBottomWindow from receiving touches
5456 mBottomWindow->assertNoEvents();
5457}
5458
5459/**
5460 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5461 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5462 */
5463TEST_F(InputDispatcherMultiWindowOcclusionTests,
5464 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5465 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5466 "Window with input channel and NO_INPUT_CHANNEL",
5467 ADISPLAY_ID_DEFAULT);
5468
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005469 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005470 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5472
5473 PointF touchedPoint = {10, 10};
5474
5475 NotifyMotionArgs motionArgs =
5476 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5477 ADISPLAY_ID_DEFAULT, {touchedPoint});
5478 mDispatcher->notifyMotion(&motionArgs);
5479
5480 mNoInputWindow->assertNoEvents();
5481 mBottomWindow->assertNoEvents();
5482}
5483
Vishnu Nair958da932020-08-21 17:12:37 -07005484class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5485protected:
5486 std::shared_ptr<FakeApplicationHandle> mApp;
5487 sp<FakeWindowHandle> mWindow;
5488 sp<FakeWindowHandle> mMirror;
5489
5490 virtual void SetUp() override {
5491 InputDispatcherTest::SetUp();
5492 mApp = std::make_shared<FakeApplicationHandle>();
5493 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5494 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5495 mWindow->getToken());
5496 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5497 mWindow->setFocusable(true);
5498 mMirror->setFocusable(true);
5499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5500 }
5501};
5502
5503TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5504 // Request focus on a mirrored window
5505 setFocusedWindow(mMirror);
5506
5507 // window gets focused
5508 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005509 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5510 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005511 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5512}
5513
5514// A focused & mirrored window remains focused only if the window and its mirror are both
5515// focusable.
5516TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5517 setFocusedWindow(mMirror);
5518
5519 // window gets focused
5520 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5522 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005523 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5525 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005526 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5527
5528 mMirror->setFocusable(false);
5529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5530
5531 // window loses focus since one of the windows associated with the token in not focusable
5532 mWindow->consumeFocusEvent(false);
5533
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005534 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5535 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005536 mWindow->assertNoEvents();
5537}
5538
5539// A focused & mirrored window remains focused until the window and its mirror both become
5540// invisible.
5541TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5542 setFocusedWindow(mMirror);
5543
5544 // window gets focused
5545 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5547 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005548 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5550 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005551 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5552
5553 mMirror->setVisible(false);
5554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5555
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5557 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005558 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5560 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005561 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5562
5563 mWindow->setVisible(false);
5564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5565
5566 // window loses focus only after all windows associated with the token become invisible.
5567 mWindow->consumeFocusEvent(false);
5568
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005569 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5570 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005571 mWindow->assertNoEvents();
5572}
5573
5574// A focused & mirrored window remains focused until both windows are removed.
5575TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5576 setFocusedWindow(mMirror);
5577
5578 // window gets focused
5579 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5581 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005582 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5584 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005585 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5586
5587 // single window is removed but the window token remains focused
5588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5589
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5591 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005592 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5594 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005595 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5596
5597 // Both windows are removed
5598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5599 mWindow->consumeFocusEvent(false);
5600
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005601 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5602 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005603 mWindow->assertNoEvents();
5604}
5605
5606// Focus request can be pending until one window becomes visible.
5607TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5608 // Request focus on an invisible mirror.
5609 mWindow->setVisible(false);
5610 mMirror->setVisible(false);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5612 setFocusedWindow(mMirror);
5613
5614 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005616 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005617 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005618
5619 mMirror->setVisible(true);
5620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5621
5622 // window gets focused
5623 mWindow->consumeFocusEvent(true);
5624 // window gets the pending key event
5625 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5626}
Prabir Pradhan99987712020-11-10 18:43:05 -08005627
5628class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5629protected:
5630 std::shared_ptr<FakeApplicationHandle> mApp;
5631 sp<FakeWindowHandle> mWindow;
5632 sp<FakeWindowHandle> mSecondWindow;
5633
5634 void SetUp() override {
5635 InputDispatcherTest::SetUp();
5636 mApp = std::make_shared<FakeApplicationHandle>();
5637 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5638 mWindow->setFocusable(true);
5639 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5640 mSecondWindow->setFocusable(true);
5641
5642 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5644
5645 setFocusedWindow(mWindow);
5646 mWindow->consumeFocusEvent(true);
5647 }
5648
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005649 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5650 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005651 mDispatcher->notifyPointerCaptureChanged(&args);
5652 }
5653
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005654 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5655 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005656 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005657 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5658 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005659 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005660 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005661 }
5662};
5663
5664TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5665 // Ensure that capture cannot be obtained for unfocused windows.
5666 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5667 mFakePolicy->assertSetPointerCaptureNotCalled();
5668 mSecondWindow->assertNoEvents();
5669
5670 // Ensure that capture can be enabled from the focus window.
5671 requestAndVerifyPointerCapture(mWindow, true);
5672
5673 // Ensure that capture cannot be disabled from a window that does not have capture.
5674 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5675 mFakePolicy->assertSetPointerCaptureNotCalled();
5676
5677 // Ensure that capture can be disabled from the window with capture.
5678 requestAndVerifyPointerCapture(mWindow, false);
5679}
5680
5681TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005682 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005683
5684 setFocusedWindow(mSecondWindow);
5685
5686 // Ensure that the capture disabled event was sent first.
5687 mWindow->consumeCaptureEvent(false);
5688 mWindow->consumeFocusEvent(false);
5689 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005690 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005691
5692 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005693 notifyPointerCaptureChanged({});
5694 notifyPointerCaptureChanged(request);
5695 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005696 mWindow->assertNoEvents();
5697 mSecondWindow->assertNoEvents();
5698 mFakePolicy->assertSetPointerCaptureNotCalled();
5699}
5700
5701TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005702 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005703
5704 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005705 notifyPointerCaptureChanged({});
5706 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005707
5708 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005709 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005710 mWindow->consumeCaptureEvent(false);
5711 mWindow->assertNoEvents();
5712}
5713
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005714TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5715 requestAndVerifyPointerCapture(mWindow, true);
5716
5717 // The first window loses focus.
5718 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005719 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005720 mWindow->consumeCaptureEvent(false);
5721
5722 // Request Pointer Capture from the second window before the notification from InputReader
5723 // arrives.
5724 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005725 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005726
5727 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005728 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005729
5730 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005731 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005732
5733 mSecondWindow->consumeFocusEvent(true);
5734 mSecondWindow->consumeCaptureEvent(true);
5735}
5736
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005737TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5738 // App repeatedly enables and disables capture.
5739 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5740 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5741 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5742 mFakePolicy->assertSetPointerCaptureCalled(false);
5743 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5744 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5745
5746 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5747 // first request is now stale, this should do nothing.
5748 notifyPointerCaptureChanged(firstRequest);
5749 mWindow->assertNoEvents();
5750
5751 // InputReader notifies that the second request was enabled.
5752 notifyPointerCaptureChanged(secondRequest);
5753 mWindow->consumeCaptureEvent(true);
5754}
5755
Prabir Pradhan7092e262022-05-03 16:51:09 +00005756TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5757 requestAndVerifyPointerCapture(mWindow, true);
5758
5759 // App toggles pointer capture off and on.
5760 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5761 mFakePolicy->assertSetPointerCaptureCalled(false);
5762
5763 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5764 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5765
5766 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5767 // preceding "disable" request.
5768 notifyPointerCaptureChanged(enableRequest);
5769
5770 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5771 // any notifications.
5772 mWindow->assertNoEvents();
5773}
5774
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005775class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5776protected:
5777 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005778
5779 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5780 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5781
5782 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5783 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5784
5785 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5786 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5787 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5788 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5789 MAXIMUM_OBSCURING_OPACITY);
5790
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005791 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005792 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005793 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005794
5795 sp<FakeWindowHandle> mTouchWindow;
5796
5797 virtual void SetUp() override {
5798 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005799 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005800 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5801 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5802 }
5803
5804 virtual void TearDown() override {
5805 InputDispatcherTest::TearDown();
5806 mTouchWindow.clear();
5807 }
5808
chaviw3277faf2021-05-19 16:45:23 -05005809 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5810 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005811 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005812 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005813 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005814 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005815 return window;
5816 }
5817
5818 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5819 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5820 sp<FakeWindowHandle> window =
5821 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5822 // Generate an arbitrary PID based on the UID
5823 window->setOwnerInfo(1777 + (uid % 10000), uid);
5824 return window;
5825 }
5826
5827 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5828 NotifyMotionArgs args =
5829 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5830 ADISPLAY_ID_DEFAULT, points);
5831 mDispatcher->notifyMotion(&args);
5832 }
5833};
5834
5835TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005836 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005837 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005839
5840 touch();
5841
5842 mTouchWindow->assertNoEvents();
5843}
5844
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005845TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005846 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5847 const sp<FakeWindowHandle>& w =
5848 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5850
5851 touch();
5852
5853 mTouchWindow->assertNoEvents();
5854}
5855
5856TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005857 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5858 const sp<FakeWindowHandle>& w =
5859 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5861
5862 touch();
5863
5864 w->assertNoEvents();
5865}
5866
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005867TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005868 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005870
5871 touch();
5872
5873 mTouchWindow->consumeAnyMotionDown();
5874}
5875
5876TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005877 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005878 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005879 w->setFrame(Rect(0, 0, 50, 50));
5880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005881
5882 touch({PointF{100, 100}});
5883
5884 mTouchWindow->consumeAnyMotionDown();
5885}
5886
5887TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005888 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005889 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005890 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5891
5892 touch();
5893
5894 mTouchWindow->consumeAnyMotionDown();
5895}
5896
5897TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5898 const sp<FakeWindowHandle>& w =
5899 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005901
5902 touch();
5903
5904 mTouchWindow->consumeAnyMotionDown();
5905}
5906
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005907TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5908 const sp<FakeWindowHandle>& w =
5909 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5910 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5911
5912 touch();
5913
5914 w->assertNoEvents();
5915}
5916
5917/**
5918 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5919 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5920 * window, the occluding window will still receive ACTION_OUTSIDE event.
5921 */
5922TEST_F(InputDispatcherUntrustedTouchesTest,
5923 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5924 const sp<FakeWindowHandle>& w =
5925 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005926 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5928
5929 touch();
5930
5931 w->consumeMotionOutside();
5932}
5933
5934TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5935 const sp<FakeWindowHandle>& w =
5936 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005937 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5939
5940 touch();
5941
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005942 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005943}
5944
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005945TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005946 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005947 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5948 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5950
5951 touch();
5952
5953 mTouchWindow->consumeAnyMotionDown();
5954}
5955
5956TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5957 const sp<FakeWindowHandle>& w =
5958 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5959 MAXIMUM_OBSCURING_OPACITY);
5960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005961
5962 touch();
5963
5964 mTouchWindow->consumeAnyMotionDown();
5965}
5966
5967TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005968 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005969 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5970 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5972
5973 touch();
5974
5975 mTouchWindow->assertNoEvents();
5976}
5977
5978TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5979 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5980 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005981 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5982 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005983 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005984 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5985 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005986 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5987
5988 touch();
5989
5990 mTouchWindow->assertNoEvents();
5991}
5992
5993TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5994 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5995 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005996 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5997 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005998 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005999 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6000 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6002
6003 touch();
6004
6005 mTouchWindow->consumeAnyMotionDown();
6006}
6007
6008TEST_F(InputDispatcherUntrustedTouchesTest,
6009 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6010 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006011 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6012 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006013 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006014 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6015 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006016 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6017
6018 touch();
6019
6020 mTouchWindow->consumeAnyMotionDown();
6021}
6022
6023TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6024 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006025 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6026 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006027 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006028 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6029 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006031
6032 touch();
6033
6034 mTouchWindow->assertNoEvents();
6035}
6036
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006037TEST_F(InputDispatcherUntrustedTouchesTest,
6038 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6039 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006040 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6041 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006042 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006043 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6044 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6046
6047 touch();
6048
6049 mTouchWindow->assertNoEvents();
6050}
6051
6052TEST_F(InputDispatcherUntrustedTouchesTest,
6053 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6054 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006055 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6056 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006057 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006058 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6059 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6061
6062 touch();
6063
6064 mTouchWindow->consumeAnyMotionDown();
6065}
6066
6067TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6068 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006069 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6070 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6072
6073 touch();
6074
6075 mTouchWindow->consumeAnyMotionDown();
6076}
6077
6078TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6079 const sp<FakeWindowHandle>& w =
6080 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6082
6083 touch();
6084
6085 mTouchWindow->consumeAnyMotionDown();
6086}
6087
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006088TEST_F(InputDispatcherUntrustedTouchesTest,
6089 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6090 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6091 const sp<FakeWindowHandle>& w =
6092 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6094
6095 touch();
6096
6097 mTouchWindow->assertNoEvents();
6098}
6099
6100TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6101 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6102 const sp<FakeWindowHandle>& w =
6103 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6105
6106 touch();
6107
6108 mTouchWindow->consumeAnyMotionDown();
6109}
6110
6111TEST_F(InputDispatcherUntrustedTouchesTest,
6112 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6113 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6114 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006115 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6116 OPACITY_ABOVE_THRESHOLD);
6117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6118
6119 touch();
6120
6121 mTouchWindow->consumeAnyMotionDown();
6122}
6123
6124TEST_F(InputDispatcherUntrustedTouchesTest,
6125 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6126 const sp<FakeWindowHandle>& w1 =
6127 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6128 OPACITY_BELOW_THRESHOLD);
6129 const sp<FakeWindowHandle>& w2 =
6130 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6131 OPACITY_BELOW_THRESHOLD);
6132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6133
6134 touch();
6135
6136 mTouchWindow->assertNoEvents();
6137}
6138
6139/**
6140 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6141 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6142 * (which alone would result in allowing touches) does not affect the blocking behavior.
6143 */
6144TEST_F(InputDispatcherUntrustedTouchesTest,
6145 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6146 const sp<FakeWindowHandle>& wB =
6147 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6148 OPACITY_BELOW_THRESHOLD);
6149 const sp<FakeWindowHandle>& wC =
6150 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6151 OPACITY_BELOW_THRESHOLD);
6152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6153
6154 touch();
6155
6156 mTouchWindow->assertNoEvents();
6157}
6158
6159/**
6160 * This test is testing that a window from a different UID but with same application token doesn't
6161 * block the touch. Apps can share the application token for close UI collaboration for example.
6162 */
6163TEST_F(InputDispatcherUntrustedTouchesTest,
6164 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6165 const sp<FakeWindowHandle>& w =
6166 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6167 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6169
6170 touch();
6171
6172 mTouchWindow->consumeAnyMotionDown();
6173}
6174
arthurhungb89ccb02020-12-30 16:19:01 +08006175class InputDispatcherDragTests : public InputDispatcherTest {
6176protected:
6177 std::shared_ptr<FakeApplicationHandle> mApp;
6178 sp<FakeWindowHandle> mWindow;
6179 sp<FakeWindowHandle> mSecondWindow;
6180 sp<FakeWindowHandle> mDragWindow;
Arthur Hung02701602022-07-15 09:35:36 +00006181 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6182 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006183
6184 void SetUp() override {
6185 InputDispatcherTest::SetUp();
6186 mApp = std::make_shared<FakeApplicationHandle>();
6187 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6188 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006189
6190 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6191 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006192
6193 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6195 }
6196
Arthur Hung02701602022-07-15 09:35:36 +00006197 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6198 switch (fromSource) {
6199 case AINPUT_SOURCE_TOUCHSCREEN:
6200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6202 ADISPLAY_ID_DEFAULT, {50, 50}))
6203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6204 break;
6205 case AINPUT_SOURCE_STYLUS:
6206 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6207 injectMotionEvent(
6208 mDispatcher,
6209 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6210 AINPUT_SOURCE_STYLUS)
6211 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6212 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6213 .x(50)
6214 .y(50))
6215 .build()));
6216 break;
6217 case AINPUT_SOURCE_MOUSE:
6218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6219 injectMotionEvent(
6220 mDispatcher,
6221 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6222 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6223 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6224 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6225 .x(50)
6226 .y(50))
6227 .build()));
6228 break;
6229 default:
6230 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6231 }
arthurhungb89ccb02020-12-30 16:19:01 +08006232
6233 // Window should receive motion event.
6234 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006235 }
6236
6237 // Start performing drag, we will create a drag window and transfer touch to it.
6238 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6239 // Returns true on success.
Arthur Hung02701602022-07-15 09:35:36 +00006240 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006241 if (sendDown) {
Arthur Hung02701602022-07-15 09:35:36 +00006242 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006243 }
arthurhungb89ccb02020-12-30 16:19:01 +08006244
6245 // The drag window covers the entire display
6246 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6247 mDispatcher->setInputWindows(
6248 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6249
6250 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006251 bool transferred =
6252 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6253 true /* isDragDrop */);
6254 if (transferred) {
6255 mWindow->consumeMotionCancel();
6256 mDragWindow->consumeMotionDown();
6257 }
6258 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006259 }
6260};
6261
6262TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hung02701602022-07-15 09:35:36 +00006263 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006264
6265 // Move on window.
6266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6267 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6268 ADISPLAY_ID_DEFAULT, {50, 50}))
6269 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6270 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6271 mWindow->consumeDragEvent(false, 50, 50);
6272 mSecondWindow->assertNoEvents();
6273
6274 // Move to another window.
6275 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6276 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6277 ADISPLAY_ID_DEFAULT, {150, 50}))
6278 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6279 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6280 mWindow->consumeDragEvent(true, 150, 50);
6281 mSecondWindow->consumeDragEvent(false, 50, 50);
6282
6283 // Move back to original window.
6284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6285 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6286 ADISPLAY_ID_DEFAULT, {50, 50}))
6287 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6288 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6289 mWindow->consumeDragEvent(false, 50, 50);
6290 mSecondWindow->consumeDragEvent(true, -50, 50);
6291
6292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6293 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6294 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6295 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6296 mWindow->assertNoEvents();
6297 mSecondWindow->assertNoEvents();
6298}
6299
arthurhungf452d0b2021-01-06 00:19:52 +08006300TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006301 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006302
6303 // Move on window.
6304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6305 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6306 ADISPLAY_ID_DEFAULT, {50, 50}))
6307 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6308 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6309 mWindow->consumeDragEvent(false, 50, 50);
6310 mSecondWindow->assertNoEvents();
6311
6312 // Move to another window.
6313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6314 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6315 ADISPLAY_ID_DEFAULT, {150, 50}))
6316 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6317 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6318 mWindow->consumeDragEvent(true, 150, 50);
6319 mSecondWindow->consumeDragEvent(false, 50, 50);
6320
6321 // drop to another window.
6322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6323 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6324 {150, 50}))
6325 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6326 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6327 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6328 mWindow->assertNoEvents();
6329 mSecondWindow->assertNoEvents();
6330}
6331
arthurhung6d4bed92021-03-17 11:59:33 +08006332TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006333 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006334
6335 // Move on window and keep button pressed.
6336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6337 injectMotionEvent(mDispatcher,
6338 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6339 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6340 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6341 .x(50)
6342 .y(50))
6343 .build()))
6344 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6345 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6346 mWindow->consumeDragEvent(false, 50, 50);
6347 mSecondWindow->assertNoEvents();
6348
6349 // Move to another window and release button, expect to drop item.
6350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6351 injectMotionEvent(mDispatcher,
6352 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6353 .buttonState(0)
6354 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6355 .x(150)
6356 .y(50))
6357 .build()))
6358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6359 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6360 mWindow->assertNoEvents();
6361 mSecondWindow->assertNoEvents();
6362 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6363
6364 // nothing to the window.
6365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6366 injectMotionEvent(mDispatcher,
6367 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6368 .buttonState(0)
6369 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6370 .x(150)
6371 .y(50))
6372 .build()))
6373 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6374 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6375 mWindow->assertNoEvents();
6376 mSecondWindow->assertNoEvents();
6377}
6378
Arthur Hung54745652022-04-20 07:17:41 +00006379TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung02701602022-07-15 09:35:36 +00006380 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006381
6382 // Set second window invisible.
6383 mSecondWindow->setVisible(false);
6384 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6385
6386 // Move on window.
6387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6388 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6389 ADISPLAY_ID_DEFAULT, {50, 50}))
6390 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6391 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6392 mWindow->consumeDragEvent(false, 50, 50);
6393 mSecondWindow->assertNoEvents();
6394
6395 // Move to another window.
6396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6397 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6398 ADISPLAY_ID_DEFAULT, {150, 50}))
6399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6400 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6401 mWindow->consumeDragEvent(true, 150, 50);
6402 mSecondWindow->assertNoEvents();
6403
6404 // drop to another window.
6405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6406 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6407 {150, 50}))
6408 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6409 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6410 mFakePolicy->assertDropTargetEquals(nullptr);
6411 mWindow->assertNoEvents();
6412 mSecondWindow->assertNoEvents();
6413}
6414
Arthur Hung54745652022-04-20 07:17:41 +00006415TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hung02701602022-07-15 09:35:36 +00006416 // Ensure window could track pointerIds if it didn't support split touch.
6417 mWindow->setPreventSplitting(true);
6418
Arthur Hung54745652022-04-20 07:17:41 +00006419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6420 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6421 {50, 50}))
6422 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6423 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6424
6425 const MotionEvent secondFingerDownEvent =
6426 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6427 .displayId(ADISPLAY_ID_DEFAULT)
6428 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6429 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6430 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6431 .build();
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6434 InputEventInjectionSync::WAIT_FOR_RESULT))
6435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6436 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6437
6438 // Should not perform drag and drop when window has multi fingers.
Arthur Hung02701602022-07-15 09:35:36 +00006439 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006440}
6441
6442TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6443 // First down on second window.
6444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6445 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6446 {150, 50}))
6447 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6448
6449 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6450
6451 // Second down on first window.
6452 const MotionEvent secondFingerDownEvent =
6453 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6454 .displayId(ADISPLAY_ID_DEFAULT)
6455 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6456 .pointer(
6457 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6458 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6459 .build();
6460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6461 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6462 InputEventInjectionSync::WAIT_FOR_RESULT))
6463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6464 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6465
6466 // Perform drag and drop from first window.
Arthur Hung02701602022-07-15 09:35:36 +00006467 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006468
6469 // Move on window.
6470 const MotionEvent secondFingerMoveEvent =
6471 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6472 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6473 .pointer(
6474 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6475 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6476 .build();
6477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6478 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6479 InputEventInjectionSync::WAIT_FOR_RESULT));
6480 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6481 mWindow->consumeDragEvent(false, 50, 50);
6482 mSecondWindow->consumeMotionMove();
6483
6484 // Release the drag pointer should perform drop.
6485 const MotionEvent secondFingerUpEvent =
6486 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6487 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6488 .pointer(
6489 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6490 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6491 .build();
6492 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6493 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6494 InputEventInjectionSync::WAIT_FOR_RESULT));
6495 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6496 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6497 mWindow->assertNoEvents();
6498 mSecondWindow->consumeMotionMove();
6499}
6500
Arthur Hung3915c1f2022-05-31 07:17:17 +00006501TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hung02701602022-07-15 09:35:36 +00006502 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006503
6504 // Update window of second display.
6505 sp<FakeWindowHandle> windowInSecondary =
6506 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6507 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6508
6509 // Let second display has a touch state.
6510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6511 injectMotionEvent(mDispatcher,
6512 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6513 AINPUT_SOURCE_TOUCHSCREEN)
6514 .displayId(SECOND_DISPLAY_ID)
6515 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6516 .x(100)
6517 .y(100))
6518 .build()));
6519 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6520 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6521 // Update window again.
6522 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6523
6524 // Move on window.
6525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6526 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6527 ADISPLAY_ID_DEFAULT, {50, 50}))
6528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6529 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6530 mWindow->consumeDragEvent(false, 50, 50);
6531 mSecondWindow->assertNoEvents();
6532
6533 // Move to another window.
6534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6535 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6536 ADISPLAY_ID_DEFAULT, {150, 50}))
6537 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6538 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6539 mWindow->consumeDragEvent(true, 150, 50);
6540 mSecondWindow->consumeDragEvent(false, 50, 50);
6541
6542 // drop to another window.
6543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6544 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6545 {150, 50}))
6546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6547 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6548 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6549 mWindow->assertNoEvents();
6550 mSecondWindow->assertNoEvents();
6551}
6552
Arthur Hung02701602022-07-15 09:35:36 +00006553TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6554 startDrag(true, AINPUT_SOURCE_MOUSE);
6555 // Move on window.
6556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6557 injectMotionEvent(mDispatcher,
6558 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6559 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6560 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6561 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6562 .x(50)
6563 .y(50))
6564 .build()))
6565 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6566 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6567 mWindow->consumeDragEvent(false, 50, 50);
6568 mSecondWindow->assertNoEvents();
6569
6570 // Move to another window.
6571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6572 injectMotionEvent(mDispatcher,
6573 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6574 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6575 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6576 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6577 .x(150)
6578 .y(50))
6579 .build()))
6580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6581 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6582 mWindow->consumeDragEvent(true, 150, 50);
6583 mSecondWindow->consumeDragEvent(false, 50, 50);
6584
6585 // drop to another window.
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionEvent(mDispatcher,
6588 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6589 .buttonState(0)
6590 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6591 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6592 .x(150)
6593 .y(50))
6594 .build()))
6595 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6596 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6597 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6598 mWindow->assertNoEvents();
6599 mSecondWindow->assertNoEvents();
6600}
6601
Vishnu Nair062a8672021-09-03 16:07:44 -07006602class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6603
6604TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6606 sp<FakeWindowHandle> window =
6607 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006608 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006609 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6610 window->setFocusable(true);
6611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6612 setFocusedWindow(window);
6613 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6614
6615 // With the flag set, window should not get any input
6616 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6617 mDispatcher->notifyKey(&keyArgs);
6618 window->assertNoEvents();
6619
6620 NotifyMotionArgs motionArgs =
6621 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6622 ADISPLAY_ID_DEFAULT);
6623 mDispatcher->notifyMotion(&motionArgs);
6624 window->assertNoEvents();
6625
6626 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006627 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6629
6630 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6631 mDispatcher->notifyKey(&keyArgs);
6632 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6633
6634 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6635 ADISPLAY_ID_DEFAULT);
6636 mDispatcher->notifyMotion(&motionArgs);
6637 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6638 window->assertNoEvents();
6639}
6640
6641TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6642 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6643 std::make_shared<FakeApplicationHandle>();
6644 sp<FakeWindowHandle> obscuringWindow =
6645 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6646 ADISPLAY_ID_DEFAULT);
6647 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6648 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006649 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006650 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6651 sp<FakeWindowHandle> window =
6652 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006653 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006654 window->setOwnerInfo(222, 222);
6655 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6656 window->setFocusable(true);
6657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6658 setFocusedWindow(window);
6659 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6660
6661 // With the flag set, window should not get any input
6662 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6663 mDispatcher->notifyKey(&keyArgs);
6664 window->assertNoEvents();
6665
6666 NotifyMotionArgs motionArgs =
6667 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6668 ADISPLAY_ID_DEFAULT);
6669 mDispatcher->notifyMotion(&motionArgs);
6670 window->assertNoEvents();
6671
6672 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006673 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6675
6676 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6677 mDispatcher->notifyKey(&keyArgs);
6678 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6679
6680 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6681 ADISPLAY_ID_DEFAULT);
6682 mDispatcher->notifyMotion(&motionArgs);
6683 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6684 window->assertNoEvents();
6685}
6686
6687TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6688 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6689 std::make_shared<FakeApplicationHandle>();
6690 sp<FakeWindowHandle> obscuringWindow =
6691 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6692 ADISPLAY_ID_DEFAULT);
6693 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6694 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006695 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006696 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6697 sp<FakeWindowHandle> window =
6698 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006699 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006700 window->setOwnerInfo(222, 222);
6701 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6702 window->setFocusable(true);
6703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6704 setFocusedWindow(window);
6705 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6706
6707 // With the flag set, window should not get any input
6708 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6709 mDispatcher->notifyKey(&keyArgs);
6710 window->assertNoEvents();
6711
6712 NotifyMotionArgs motionArgs =
6713 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6714 ADISPLAY_ID_DEFAULT);
6715 mDispatcher->notifyMotion(&motionArgs);
6716 window->assertNoEvents();
6717
6718 // When the window is no longer obscured because it went on top, it should get input
6719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6720
6721 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6722 mDispatcher->notifyKey(&keyArgs);
6723 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6724
6725 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6726 ADISPLAY_ID_DEFAULT);
6727 mDispatcher->notifyMotion(&motionArgs);
6728 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6729 window->assertNoEvents();
6730}
6731
Antonio Kantekf16f2832021-09-28 04:39:20 +00006732class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6733protected:
6734 std::shared_ptr<FakeApplicationHandle> mApp;
6735 sp<FakeWindowHandle> mWindow;
6736 sp<FakeWindowHandle> mSecondWindow;
6737
6738 void SetUp() override {
6739 InputDispatcherTest::SetUp();
6740
6741 mApp = std::make_shared<FakeApplicationHandle>();
6742 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6743 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006744 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006745 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6746 mSecondWindow->setFocusable(true);
6747
6748 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006750 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006751
6752 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00006753 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6754 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006755 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6756 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6757 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006758 }
6759
Antonio Kantekea47acb2021-12-23 12:41:25 -08006760 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006761 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006762 mWindow->consumeTouchModeEvent(inTouchMode);
6763 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6764 }
6765};
6766
Antonio Kantek26defcf2022-02-08 01:12:27 +00006767TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006768 const WindowInfo& windowInfo = *mWindow->getInfo();
6769 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6770 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006771}
6772
Antonio Kantek26defcf2022-02-08 01:12:27 +00006773TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6774 const WindowInfo& windowInfo = *mWindow->getInfo();
6775 int32_t ownerPid = windowInfo.ownerPid;
6776 int32_t ownerUid = windowInfo.ownerUid;
6777 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6778 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6779 ownerUid, /* hasPermission */ false));
6780 mWindow->assertNoEvents();
6781 mSecondWindow->assertNoEvents();
6782}
6783
6784TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6785 const WindowInfo& windowInfo = *mWindow->getInfo();
6786 int32_t ownerPid = windowInfo.ownerPid;
6787 int32_t ownerUid = windowInfo.ownerUid;
6788 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6789 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6790 /* hasPermission */ true);
6791}
6792
Antonio Kantekf16f2832021-09-28 04:39:20 +00006793TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006794 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006795 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6796 windowInfo.ownerPid, windowInfo.ownerUid,
6797 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006798 mWindow->assertNoEvents();
6799 mSecondWindow->assertNoEvents();
6800}
6801
Antonio Kantek48710e42022-03-24 14:19:30 -07006802TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6803 // Interact with the window first.
6804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6805 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6806 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6807
6808 // Then remove focus.
6809 mWindow->setFocusable(false);
6810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6811
6812 // Assert that caller can switch touch mode by owning one of the last interacted window.
6813 const WindowInfo& windowInfo = *mWindow->getInfo();
6814 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6815 windowInfo.ownerPid, windowInfo.ownerUid,
6816 /* hasPermission= */ false));
6817}
6818
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006819class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6820public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006821 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006822 std::shared_ptr<FakeApplicationHandle> application =
6823 std::make_shared<FakeApplicationHandle>();
6824 std::string name = "Fake Spy ";
6825 name += std::to_string(mSpyCount++);
6826 sp<FakeWindowHandle> spy =
6827 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006828 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006829 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006830 return spy;
6831 }
6832
6833 sp<FakeWindowHandle> createForeground() {
6834 std::shared_ptr<FakeApplicationHandle> application =
6835 std::make_shared<FakeApplicationHandle>();
6836 sp<FakeWindowHandle> window =
6837 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006838 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006839 return window;
6840 }
6841
6842private:
6843 int mSpyCount{0};
6844};
6845
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006846using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006847/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006848 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6849 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006850TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6851 ScopedSilentDeath _silentDeath;
6852
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006853 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006854 spy->setTrustedOverlay(false);
6855 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6856 ".* not a trusted overlay");
6857}
6858
6859/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006860 * Input injection into a display with a spy window but no foreground windows should succeed.
6861 */
6862TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006863 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6865
6866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6869 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6870}
6871
6872/**
6873 * Verify the order in which different input windows receive events. The touched foreground window
6874 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6875 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6876 * receive events before ones belows it.
6877 *
6878 * Here, we set up a scenario with four windows in the following Z order from the top:
6879 * spy1, spy2, window, spy3.
6880 * We then inject an event and verify that the foreground "window" receives it first, followed by
6881 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6882 * window.
6883 */
6884TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6885 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006886 auto spy1 = createSpy();
6887 auto spy2 = createSpy();
6888 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6890 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6891 const size_t numChannels = channels.size();
6892
Michael Wright8e9a8562022-02-09 13:44:29 +00006893 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006894 if (!epollFd.ok()) {
6895 FAIL() << "Failed to create epoll fd";
6896 }
6897
6898 for (size_t i = 0; i < numChannels; i++) {
6899 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6900 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6901 FAIL() << "Failed to add fd to epoll";
6902 }
6903 }
6904
6905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6908
6909 std::vector<size_t> eventOrder;
6910 std::vector<struct epoll_event> events(numChannels);
6911 for (;;) {
6912 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6913 (100ms).count());
6914 if (nFds < 0) {
6915 FAIL() << "Failed to call epoll_wait";
6916 }
6917 if (nFds == 0) {
6918 break; // epoll_wait timed out
6919 }
6920 for (int i = 0; i < nFds; i++) {
6921 ASSERT_EQ(EPOLLIN, events[i].events);
6922 eventOrder.push_back(events[i].data.u64);
6923 channels[i]->consumeMotionDown();
6924 }
6925 }
6926
6927 // Verify the order in which the events were received.
6928 EXPECT_EQ(3u, eventOrder.size());
6929 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6930 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6931 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6932}
6933
6934/**
6935 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6936 */
6937TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6938 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006939 auto spy = createSpy();
6940 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6942
6943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6944 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6946 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6947 spy->assertNoEvents();
6948}
6949
6950/**
6951 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6952 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6953 * to the window.
6954 */
6955TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6956 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006957 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006958 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6960
6961 // Inject an event outside the spy window's touchable region.
6962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6963 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6965 window->consumeMotionDown();
6966 spy->assertNoEvents();
6967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6968 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6969 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6970 window->consumeMotionUp();
6971 spy->assertNoEvents();
6972
6973 // Inject an event inside the spy window's touchable region.
6974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6975 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6976 {5, 10}))
6977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6978 window->consumeMotionDown();
6979 spy->consumeMotionDown();
6980}
6981
6982/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006983 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006984 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006985 */
6986TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6987 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006988 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006989 auto spy = createSpy();
6990 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006991 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006992 spy->setFrame(Rect{0, 0, 20, 20});
6993 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6994
6995 // Inject an event outside the spy window's frame and touchable region.
6996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6998 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006999 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7000 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007001 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007002}
7003
7004/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007005 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
7006 * any other windows - including other spy windows - will also be cancelled.
7007 */
7008TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
7009 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007010 auto spy1 = createSpy();
7011 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7013
7014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7017 window->consumeMotionDown();
7018 spy1->consumeMotionDown();
7019 spy2->consumeMotionDown();
7020
7021 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007022 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007023 spy2->assertNoEvents();
7024 spy1->consumeMotionCancel();
7025 window->consumeMotionCancel();
7026
7027 // The rest of the gesture should only be sent to the second spy window.
7028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7029 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7030 ADISPLAY_ID_DEFAULT))
7031 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7032 spy2->consumeMotionMove();
7033 spy1->assertNoEvents();
7034 window->assertNoEvents();
7035}
7036
7037/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007038 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7039 * in the middle of the gesture.
7040 */
7041TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
7042 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007043 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7045
7046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7047 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7049 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7050 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7051
7052 window->releaseChannel();
7053
7054 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7055
7056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7057 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7059 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7060}
7061
7062/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007063 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7064 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007065 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007066TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007067 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007068 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007069
7070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7071
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007072 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7074 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7075 {100, 200}))
7076 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007077 spy->consumeMotionDown();
7078 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007079
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007080 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007081 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007082 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007083
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007084 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007085 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007086 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007087 .displayId(ADISPLAY_ID_DEFAULT)
7088 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7089 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7090 .x(100)
7091 .y(200))
7092 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7093 .build();
7094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7095 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7096 InputEventInjectionSync::WAIT_FOR_RESULT))
7097 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7098
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007099 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7100
7101 // Third finger goes down outside all windows, so injection should fail.
7102 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00007103 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007104 .displayId(ADISPLAY_ID_DEFAULT)
7105 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7106 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7107 .x(100)
7108 .y(200))
7109 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7110 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7111 .build();
7112 ASSERT_EQ(InputEventInjectionResult::FAILED,
7113 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7114 InputEventInjectionSync::WAIT_FOR_RESULT))
7115 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7116
7117 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007118 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007119}
7120
7121/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007122 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7123 * pointers that are down within its bounds.
7124 */
7125TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7126 auto windowLeft = createForeground();
7127 windowLeft->setFrame({0, 0, 100, 200});
7128 auto windowRight = createForeground();
7129 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007130 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007131 spy->setFrame({0, 0, 200, 200});
7132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7133
7134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7135 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7136 {50, 50}))
7137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7138 windowLeft->consumeMotionDown();
7139 spy->consumeMotionDown();
7140
7141 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007142 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007143 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7144 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7145 .pointer(
7146 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7147 .build();
7148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7149 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7150 InputEventInjectionSync::WAIT_FOR_RESULT))
7151 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7152 windowRight->consumeMotionDown();
7153 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7154}
7155
7156/**
7157 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7158 * the spy should receive the second pointer with ACTION_DOWN.
7159 */
7160TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7161 auto window = createForeground();
7162 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007163 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007164 spyRight->setFrame({100, 0, 200, 200});
7165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7166
7167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7168 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7169 {50, 50}))
7170 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7171 window->consumeMotionDown();
7172 spyRight->assertNoEvents();
7173
7174 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007175 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007176 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7177 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7178 .pointer(
7179 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7180 .build();
7181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7182 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7183 InputEventInjectionSync::WAIT_FOR_RESULT))
7184 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7185 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7186 spyRight->consumeMotionDown();
7187}
7188
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007189/**
7190 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7191 * windows should be allowed to control split touch.
7192 */
7193TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007194 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007195 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007196 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007197 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007198
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007199 auto window = createForeground();
7200 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007201
7202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7203
7204 // First finger down, no window touched.
7205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7206 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7207 {100, 200}))
7208 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7209 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7210 window->assertNoEvents();
7211
7212 // Second finger down on window, the window should receive touch down.
7213 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007214 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007215 .displayId(ADISPLAY_ID_DEFAULT)
7216 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7217 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7218 .x(100)
7219 .y(200))
7220 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7221 .build();
7222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7223 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7224 InputEventInjectionSync::WAIT_FOR_RESULT))
7225 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7226
7227 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7228 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7229}
7230
7231/**
7232 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7233 * do not receive key events.
7234 */
7235TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007236 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007237 spy->setFocusable(false);
7238
7239 auto window = createForeground();
7240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7241 setFocusedWindow(window);
7242 window->consumeFocusEvent(true);
7243
7244 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7245 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7246 window->consumeKeyDown(ADISPLAY_ID_NONE);
7247
7248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7249 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7250 window->consumeKeyUp(ADISPLAY_ID_NONE);
7251
7252 spy->assertNoEvents();
7253}
7254
Prabir Pradhand65552b2021-10-07 11:23:50 -07007255class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7256public:
7257 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7258 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7259 std::make_shared<FakeApplicationHandle>();
7260 sp<FakeWindowHandle> overlay =
7261 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7262 ADISPLAY_ID_DEFAULT);
7263 overlay->setFocusable(false);
7264 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007265 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007266 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007267 overlay->setTrustedOverlay(true);
7268
7269 std::shared_ptr<FakeApplicationHandle> application =
7270 std::make_shared<FakeApplicationHandle>();
7271 sp<FakeWindowHandle> window =
7272 new FakeWindowHandle(application, mDispatcher, "Application window",
7273 ADISPLAY_ID_DEFAULT);
7274 window->setFocusable(true);
7275 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007276
7277 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7279 setFocusedWindow(window);
7280 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7281 return {std::move(overlay), std::move(window)};
7282 }
7283
7284 void sendFingerEvent(int32_t action) {
7285 NotifyMotionArgs motionArgs =
7286 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7287 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7288 mDispatcher->notifyMotion(&motionArgs);
7289 }
7290
7291 void sendStylusEvent(int32_t action) {
7292 NotifyMotionArgs motionArgs =
7293 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7294 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7295 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7296 mDispatcher->notifyMotion(&motionArgs);
7297 }
7298};
7299
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007300using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7301
7302TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7303 ScopedSilentDeath _silentDeath;
7304
Prabir Pradhand65552b2021-10-07 11:23:50 -07007305 auto [overlay, window] = setupStylusOverlayScenario();
7306 overlay->setTrustedOverlay(false);
7307 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7308 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7309 ".* not a trusted overlay");
7310}
7311
7312TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7313 auto [overlay, window] = setupStylusOverlayScenario();
7314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7315
7316 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7317 overlay->consumeMotionDown();
7318 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7319 overlay->consumeMotionUp();
7320
7321 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7322 window->consumeMotionDown();
7323 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7324 window->consumeMotionUp();
7325
7326 overlay->assertNoEvents();
7327 window->assertNoEvents();
7328}
7329
7330TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7331 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007332 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7334
7335 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7336 overlay->consumeMotionDown();
7337 window->consumeMotionDown();
7338 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7339 overlay->consumeMotionUp();
7340 window->consumeMotionUp();
7341
7342 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7343 window->consumeMotionDown();
7344 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7345 window->consumeMotionUp();
7346
7347 overlay->assertNoEvents();
7348 window->assertNoEvents();
7349}
7350
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007351/**
7352 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7353 * The scenario is as follows:
7354 * - The stylus interceptor overlay is configured as a spy window.
7355 * - The stylus interceptor spy receives the start of a new stylus gesture.
7356 * - It pilfers pointers and then configures itself to no longer be a spy.
7357 * - The stylus interceptor continues to receive the rest of the gesture.
7358 */
7359TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7360 auto [overlay, window] = setupStylusOverlayScenario();
7361 overlay->setSpy(true);
7362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7363
7364 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7365 overlay->consumeMotionDown();
7366 window->consumeMotionDown();
7367
7368 // The interceptor pilfers the pointers.
7369 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7370 window->consumeMotionCancel();
7371
7372 // The interceptor configures itself so that it is no longer a spy.
7373 overlay->setSpy(false);
7374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7375
7376 // It continues to receive the rest of the stylus gesture.
7377 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7378 overlay->consumeMotionMove();
7379 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7380 overlay->consumeMotionUp();
7381
7382 window->assertNoEvents();
7383}
7384
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007385struct User {
7386 int32_t mPid;
7387 int32_t mUid;
7388 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7389 std::unique_ptr<InputDispatcher>& mDispatcher;
7390
7391 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7392 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7393
7394 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7395 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7396 ADISPLAY_ID_DEFAULT, {100, 200},
7397 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7398 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7399 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7400 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7401 }
7402
7403 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7404 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7405 InputEventInjectionSync::WAIT_FOR_RESULT,
7406 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7407 mPolicyFlags);
7408 }
7409
7410 sp<FakeWindowHandle> createWindow() const {
7411 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7412 std::make_shared<FakeApplicationHandle>();
7413 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7414 "Owned Window", ADISPLAY_ID_DEFAULT);
7415 window->setOwnerInfo(mPid, mUid);
7416 return window;
7417 }
7418};
7419
7420using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7421
7422TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7423 auto owner = User(mDispatcher, 10, 11);
7424 auto window = owner.createWindow();
7425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7426
7427 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7428 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7429 window->consumeMotionDown();
7430
7431 setFocusedWindow(window);
7432 window->consumeFocusEvent(true);
7433
7434 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7435 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7436 window->consumeKeyDown(ADISPLAY_ID_NONE);
7437}
7438
7439TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7440 auto owner = User(mDispatcher, 10, 11);
7441 auto window = owner.createWindow();
7442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7443
7444 auto rando = User(mDispatcher, 20, 21);
7445 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7446 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7447
7448 setFocusedWindow(window);
7449 window->consumeFocusEvent(true);
7450
7451 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7452 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7453 window->assertNoEvents();
7454}
7455
7456TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7457 auto owner = User(mDispatcher, 10, 11);
7458 auto window = owner.createWindow();
7459 auto spy = owner.createWindow();
7460 spy->setSpy(true);
7461 spy->setTrustedOverlay(true);
7462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7463
7464 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7465 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7466 spy->consumeMotionDown();
7467 window->consumeMotionDown();
7468}
7469
7470TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7471 auto owner = User(mDispatcher, 10, 11);
7472 auto window = owner.createWindow();
7473
7474 auto rando = User(mDispatcher, 20, 21);
7475 auto randosSpy = rando.createWindow();
7476 randosSpy->setSpy(true);
7477 randosSpy->setTrustedOverlay(true);
7478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7479
7480 // The event is targeted at owner's window, so injection should succeed, but the spy should
7481 // not receive the event.
7482 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7483 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7484 randosSpy->assertNoEvents();
7485 window->consumeMotionDown();
7486}
7487
7488TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7489 auto owner = User(mDispatcher, 10, 11);
7490 auto window = owner.createWindow();
7491
7492 auto rando = User(mDispatcher, 20, 21);
7493 auto randosSpy = rando.createWindow();
7494 randosSpy->setSpy(true);
7495 randosSpy->setTrustedOverlay(true);
7496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7497
7498 // A user that has injection permission can inject into any window.
7499 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7500 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7501 ADISPLAY_ID_DEFAULT));
7502 randosSpy->consumeMotionDown();
7503 window->consumeMotionDown();
7504
7505 setFocusedWindow(randosSpy);
7506 randosSpy->consumeFocusEvent(true);
7507
7508 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7509 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7510 window->assertNoEvents();
7511}
7512
7513TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7514 auto owner = User(mDispatcher, 10, 11);
7515 auto window = owner.createWindow();
7516
7517 auto rando = User(mDispatcher, 20, 21);
7518 auto randosWindow = rando.createWindow();
7519 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7520 randosWindow->setWatchOutsideTouch(true);
7521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7522
7523 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7524 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7525 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7526 window->consumeMotionDown();
7527 randosWindow->consumeMotionOutside();
7528}
7529
Garfield Tane84e6f92019-08-29 17:28:41 -07007530} // namespace android::inputdispatcher