blob: 58617f7383973ef06f84af1ead824457c23c50eb [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
Arthur Hung69d75572022-11-15 03:30:48 +00001890TEST_F(InputDispatcherTest, WallpaperWindowReceivesMultiTouch) {
1891 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1892 sp<FakeWindowHandle> window =
1893 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1894 window->setDupTouchToWallpaper(true);
1895
1896 sp<FakeWindowHandle> wallpaperWindow =
1897 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1898 wallpaperWindow->setIsWallpaper(true);
1899 constexpr int expectedWallpaperFlags =
1900 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1901 wallpaperWindow->setPreventSplitting(true);
1902
1903 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1904
1905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1907 {50, 50}))
1908 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1909 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1910 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1911
1912 const MotionEvent secondFingerDownEvent =
1913 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
1914 .displayId(ADISPLAY_ID_DEFAULT)
1915 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1916 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
1917 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
1918 .build();
1919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1920 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1921 InputEventInjectionSync::WAIT_FOR_RESULT))
1922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1923
1924 window->consumeMotionPointerDown(1);
1925 wallpaperWindow->consumeMotionPointerDown(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1926
1927 const MotionEvent secondFingerUpEvent =
1928 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
1929 .displayId(ADISPLAY_ID_DEFAULT)
1930 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1931 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
1932 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
1933 .build();
1934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1935 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
1936 InputEventInjectionSync::WAIT_FOR_RESULT))
1937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1938 window->consumeMotionPointerUp(1);
1939 wallpaperWindow->consumeMotionPointerUp(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1940
1941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1942 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
1943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1944 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1945 wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1946}
1947
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001948/**
1949 * On the display, have a single window, and also an area where there's no window.
1950 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1951 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1952 */
1953TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1954 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1955 sp<FakeWindowHandle> window =
1956 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1957
1958 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1959 NotifyMotionArgs args;
1960
1961 // Touch down on the empty space
1962 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1963
1964 mDispatcher->waitForIdle();
1965 window->assertNoEvents();
1966
1967 // Now touch down on the window with another pointer
1968 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1969 mDispatcher->waitForIdle();
1970 window->consumeMotionDown();
1971}
1972
1973/**
1974 * Same test as above, but instead of touching the empty space, the first touch goes to
1975 * non-touchable window.
1976 */
1977TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1978 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1979 sp<FakeWindowHandle> window1 =
1980 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1981 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1982 window1->setTouchable(false);
1983 sp<FakeWindowHandle> window2 =
1984 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1985 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1986
1987 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1988
1989 NotifyMotionArgs args;
1990 // Touch down on the non-touchable window
1991 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1992
1993 mDispatcher->waitForIdle();
1994 window1->assertNoEvents();
1995 window2->assertNoEvents();
1996
1997 // Now touch down on the window with another pointer
1998 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1999 mDispatcher->waitForIdle();
2000 window2->consumeMotionDown();
2001}
2002
Garfield Tandf26e862020-07-01 20:18:19 -07002003TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002004 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002005 sp<FakeWindowHandle> windowLeft =
2006 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2007 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002008 sp<FakeWindowHandle> windowRight =
2009 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2010 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002011
2012 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2013
2014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2015
2016 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002018 injectMotionEvent(mDispatcher,
2019 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2020 AINPUT_SOURCE_MOUSE)
2021 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2022 .x(900)
2023 .y(400))
2024 .build()));
2025 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2026 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2027 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2028 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2029
2030 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002032 injectMotionEvent(mDispatcher,
2033 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2034 AINPUT_SOURCE_MOUSE)
2035 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2036 .x(300)
2037 .y(400))
2038 .build()));
2039 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2040 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2041 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2042 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2043 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2044 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2045
2046 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002048 injectMotionEvent(mDispatcher,
2049 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2050 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2051 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2052 .x(300)
2053 .y(400))
2054 .build()));
2055 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2056
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002058 injectMotionEvent(mDispatcher,
2059 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2060 AINPUT_SOURCE_MOUSE)
2061 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2062 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2063 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2064 .x(300)
2065 .y(400))
2066 .build()));
2067 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2068 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2069
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002071 injectMotionEvent(mDispatcher,
2072 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2073 AINPUT_SOURCE_MOUSE)
2074 .buttonState(0)
2075 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2076 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2077 .x(300)
2078 .y(400))
2079 .build()));
2080 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2081 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2082
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002084 injectMotionEvent(mDispatcher,
2085 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2086 .buttonState(0)
2087 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2088 .x(300)
2089 .y(400))
2090 .build()));
2091 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2092
2093 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002095 injectMotionEvent(mDispatcher,
2096 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2097 AINPUT_SOURCE_MOUSE)
2098 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2099 .x(900)
2100 .y(400))
2101 .build()));
2102 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2103 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2104 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2105 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2106 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2107 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2108}
2109
2110// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2111// directly in this test.
2112TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002113 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002114 sp<FakeWindowHandle> window =
2115 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2116 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002117
2118 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2119
2120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
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_ENTER,
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_ENTER,
2131 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2132
2133 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002135 injectMotionEvent(mDispatcher,
2136 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2137 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2138 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2139 .x(300)
2140 .y(400))
2141 .build()));
2142 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2143
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002145 injectMotionEvent(mDispatcher,
2146 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2147 AINPUT_SOURCE_MOUSE)
2148 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2149 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2150 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2151 .x(300)
2152 .y(400))
2153 .build()));
2154 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2155 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2156
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002157 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002158 injectMotionEvent(mDispatcher,
2159 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2160 AINPUT_SOURCE_MOUSE)
2161 .buttonState(0)
2162 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2163 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2164 .x(300)
2165 .y(400))
2166 .build()));
2167 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2168 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2169
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002171 injectMotionEvent(mDispatcher,
2172 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2173 .buttonState(0)
2174 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2175 .x(300)
2176 .y(400))
2177 .build()));
2178 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002181 injectMotionEvent(mDispatcher,
2182 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2183 AINPUT_SOURCE_MOUSE)
2184 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2185 .x(300)
2186 .y(400))
2187 .build()));
2188 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2189 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2190}
2191
Garfield Tan00f511d2019-06-12 16:55:40 -07002192TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002193 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002194
2195 sp<FakeWindowHandle> windowLeft =
2196 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2197 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002198 sp<FakeWindowHandle> windowRight =
2199 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2200 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002201
2202 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2203
Arthur Hung72d8dc32020-03-28 00:48:39 +00002204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002205
2206 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2207 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002209 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002210 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002211 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002212 windowRight->assertNoEvents();
2213}
2214
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002215TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002216 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002217 sp<FakeWindowHandle> window =
2218 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002219 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002220
Arthur Hung72d8dc32020-03-28 00:48:39 +00002221 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002222 setFocusedWindow(window);
2223
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002224 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002225
2226 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2227 mDispatcher->notifyKey(&keyArgs);
2228
2229 // Window should receive key down event.
2230 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2231
2232 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2233 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002234 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002235 mDispatcher->notifyDeviceReset(&args);
2236 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2237 AKEY_EVENT_FLAG_CANCELED);
2238}
2239
2240TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002241 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002242 sp<FakeWindowHandle> window =
2243 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2244
Arthur Hung72d8dc32020-03-28 00:48:39 +00002245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002246
2247 NotifyMotionArgs motionArgs =
2248 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2249 ADISPLAY_ID_DEFAULT);
2250 mDispatcher->notifyMotion(&motionArgs);
2251
2252 // Window should receive motion down event.
2253 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2254
2255 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2256 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002257 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002258 mDispatcher->notifyDeviceReset(&args);
2259 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2260 0 /*expectedFlags*/);
2261}
2262
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002263TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2264 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2265 sp<FakeWindowHandle> window =
2266 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2267 window->setFocusable(true);
2268
2269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2270 setFocusedWindow(window);
2271
2272 window->consumeFocusEvent(true);
2273
2274 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2275 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2276 const nsecs_t injectTime = keyArgs.eventTime;
2277 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2278 mDispatcher->notifyKey(&keyArgs);
2279 // The dispatching time should be always greater than or equal to intercept key timeout.
2280 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2281 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2282 std::chrono::nanoseconds(interceptKeyTimeout).count());
2283}
2284
2285TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2286 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2287 sp<FakeWindowHandle> window =
2288 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2289 window->setFocusable(true);
2290
2291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2292 setFocusedWindow(window);
2293
2294 window->consumeFocusEvent(true);
2295
2296 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2297 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2298 mFakePolicy->setInterceptKeyTimeout(150ms);
2299 mDispatcher->notifyKey(&keyDown);
2300 mDispatcher->notifyKey(&keyUp);
2301
2302 // Window should receive key event immediately when same key up.
2303 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2304 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2305}
2306
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002307/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002308 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2309 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2310 * ACTION_OUTSIDE event is sent per gesture.
2311 */
2312TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2313 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2314 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2315 sp<FakeWindowHandle> window =
2316 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2317 window->setWatchOutsideTouch(true);
2318 window->setFrame(Rect{0, 0, 100, 100});
2319 sp<FakeWindowHandle> secondWindow =
2320 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2321 secondWindow->setFrame(Rect{100, 100, 200, 200});
2322 sp<FakeWindowHandle> thirdWindow =
2323 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2324 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2326
2327 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2328 NotifyMotionArgs motionArgs =
2329 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2330 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2331 mDispatcher->notifyMotion(&motionArgs);
2332 window->assertNoEvents();
2333 secondWindow->assertNoEvents();
2334
2335 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2336 // Now, `window` should get ACTION_OUTSIDE.
2337 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2338 {PointF{-10, -10}, PointF{105, 105}});
2339 mDispatcher->notifyMotion(&motionArgs);
2340 window->consumeMotionOutside();
2341 secondWindow->consumeMotionDown();
2342 thirdWindow->assertNoEvents();
2343
2344 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2345 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2346 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2347 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2348 mDispatcher->notifyMotion(&motionArgs);
2349 window->assertNoEvents();
2350 secondWindow->consumeMotionMove();
2351 thirdWindow->consumeMotionDown();
2352}
2353
Prabir Pradhan73fe4812022-07-22 20:22:18 +00002354TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2355 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2356 sp<FakeWindowHandle> window =
2357 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2358 window->setFocusable(true);
2359
2360 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2361 setFocusedWindow(window);
2362
2363 window->consumeFocusEvent(true);
2364
2365 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2366 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2367 mDispatcher->notifyKey(&keyDown);
2368 mDispatcher->notifyKey(&keyUp);
2369
2370 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2371 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2372
2373 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2374 mDispatcher->onWindowInfosChanged({}, {});
2375
2376 window->consumeFocusEvent(false);
2377
2378 mDispatcher->notifyKey(&keyDown);
2379 mDispatcher->notifyKey(&keyUp);
2380 window->assertNoEvents();
2381}
2382
Arthur Hung69d75572022-11-15 03:30:48 +00002383TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2385 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2386 "Fake Window", ADISPLAY_ID_DEFAULT);
2387 // Ensure window is non-split and have some transform.
2388 window->setPreventSplitting(true);
2389 window->setWindowOffset(20, 40);
2390 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2391
2392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2394 {50, 50}))
2395 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2396 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2397
2398 const MotionEvent secondFingerDownEvent =
2399 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2400 .displayId(ADISPLAY_ID_DEFAULT)
2401 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2402 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2403 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2404 .x(-30)
2405 .y(-50))
2406 .build();
2407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2408 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2409 InputEventInjectionSync::WAIT_FOR_RESULT))
2410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2411
2412 const MotionEvent* event = window->consumeMotion();
2413 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2414 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2415 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2416 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2417 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2418}
2419
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002420/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002421 * Ensure the correct coordinate spaces are used by InputDispatcher.
2422 *
2423 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2424 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2425 * space.
2426 */
2427class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2428public:
2429 void SetUp() override {
2430 InputDispatcherTest::SetUp();
2431 mDisplayInfos.clear();
2432 mWindowInfos.clear();
2433 }
2434
2435 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2436 gui::DisplayInfo info;
2437 info.displayId = displayId;
2438 info.transform = transform;
2439 mDisplayInfos.push_back(std::move(info));
2440 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2441 }
2442
2443 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2444 mWindowInfos.push_back(*windowHandle->getInfo());
2445 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2446 }
2447
2448 // Set up a test scenario where the display has a scaled projection and there are two windows
2449 // on the display.
2450 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2451 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2452 // respectively.
2453 ui::Transform displayTransform;
2454 displayTransform.set(2, 0, 0, 4);
2455 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2456
2457 std::shared_ptr<FakeApplicationHandle> application =
2458 std::make_shared<FakeApplicationHandle>();
2459
2460 // Add two windows to the display. Their frames are represented in the display space.
2461 sp<FakeWindowHandle> firstWindow =
2462 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002463 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2464 addWindow(firstWindow);
2465
2466 sp<FakeWindowHandle> secondWindow =
2467 new FakeWindowHandle(application, mDispatcher, "Second Window",
2468 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002469 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2470 addWindow(secondWindow);
2471 return {std::move(firstWindow), std::move(secondWindow)};
2472 }
2473
2474private:
2475 std::vector<gui::DisplayInfo> mDisplayInfos;
2476 std::vector<gui::WindowInfo> mWindowInfos;
2477};
2478
2479TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2480 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2481 // Send down to the first window. The point is represented in the display space. The point is
2482 // selected so that if the hit test was done with the transform applied to it, then it would
2483 // end up in the incorrect window.
2484 NotifyMotionArgs downMotionArgs =
2485 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2486 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2487 mDispatcher->notifyMotion(&downMotionArgs);
2488
2489 firstWindow->consumeMotionDown();
2490 secondWindow->assertNoEvents();
2491}
2492
2493// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2494// the event should be treated as being in the logical display space.
2495TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2496 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2497 // Send down to the first window. The point is represented in the logical display space. The
2498 // point is selected so that if the hit test was done in logical display space, then it would
2499 // end up in the incorrect window.
2500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2501 PointF{75 * 2, 55 * 4});
2502
2503 firstWindow->consumeMotionDown();
2504 secondWindow->assertNoEvents();
2505}
2506
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002507// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2508// event should be treated as being in the logical display space.
2509TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2510 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2511
2512 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2513 ui::Transform injectedEventTransform;
2514 injectedEventTransform.set(matrix);
2515 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2516 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2517
2518 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2519 .displayId(ADISPLAY_ID_DEFAULT)
2520 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2521 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2522 .x(untransformedPoint.x)
2523 .y(untransformedPoint.y))
2524 .build();
2525 event.transform(matrix);
2526
2527 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2528 InputEventInjectionSync::WAIT_FOR_RESULT);
2529
2530 firstWindow->consumeMotionDown();
2531 secondWindow->assertNoEvents();
2532}
2533
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002534TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2535 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2536
2537 // Send down to the second window.
2538 NotifyMotionArgs downMotionArgs =
2539 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2540 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2541 mDispatcher->notifyMotion(&downMotionArgs);
2542
2543 firstWindow->assertNoEvents();
2544 const MotionEvent* event = secondWindow->consumeMotion();
2545 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2546
2547 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2548 EXPECT_EQ(300, event->getRawX(0));
2549 EXPECT_EQ(880, event->getRawY(0));
2550
2551 // Ensure that the x and y values are in the window's coordinate space.
2552 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2553 // the logical display space. This will be the origin of the window space.
2554 EXPECT_EQ(100, event->getX(0));
2555 EXPECT_EQ(80, event->getY(0));
2556}
2557
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002558using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2559 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002560
2561class TransferTouchFixture : public InputDispatcherTest,
2562 public ::testing::WithParamInterface<TransferFunction> {};
2563
2564TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002565 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002566
2567 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002568 sp<FakeWindowHandle> firstWindow =
2569 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2570 sp<FakeWindowHandle> secondWindow =
2571 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002572
2573 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002575
2576 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002577 NotifyMotionArgs downMotionArgs =
2578 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2579 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002580 mDispatcher->notifyMotion(&downMotionArgs);
2581 // Only the first window should get the down event
2582 firstWindow->consumeMotionDown();
2583 secondWindow->assertNoEvents();
2584
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002585 // Transfer touch to the second window
2586 TransferFunction f = GetParam();
2587 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2588 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002589 // The first window gets cancel and the second gets down
2590 firstWindow->consumeMotionCancel();
2591 secondWindow->consumeMotionDown();
2592
2593 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002594 NotifyMotionArgs upMotionArgs =
2595 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2596 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002597 mDispatcher->notifyMotion(&upMotionArgs);
2598 // The first window gets no events and the second gets up
2599 firstWindow->assertNoEvents();
2600 secondWindow->consumeMotionUp();
2601}
2602
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002603/**
2604 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2605 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2606 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2607 * natural to the user.
2608 * In this test, we are sending a pointer to both spy window and first window. We then try to
2609 * transfer touch to the second window. The dispatcher should identify the first window as the
2610 * one that should lose the gesture, and therefore the action should be to move the gesture from
2611 * the first window to the second.
2612 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2613 * the other API, as well.
2614 */
2615TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2617
2618 // Create a couple of windows + a spy window
2619 sp<FakeWindowHandle> spyWindow =
2620 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2621 spyWindow->setTrustedOverlay(true);
2622 spyWindow->setSpy(true);
2623 sp<FakeWindowHandle> firstWindow =
2624 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2625 sp<FakeWindowHandle> secondWindow =
2626 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2627
2628 // Add the windows to the dispatcher
2629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2630
2631 // Send down to the first window
2632 NotifyMotionArgs downMotionArgs =
2633 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2634 ADISPLAY_ID_DEFAULT);
2635 mDispatcher->notifyMotion(&downMotionArgs);
2636 // Only the first window and spy should get the down event
2637 spyWindow->consumeMotionDown();
2638 firstWindow->consumeMotionDown();
2639
2640 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2641 // if f === 'transferTouch'.
2642 TransferFunction f = GetParam();
2643 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2644 ASSERT_TRUE(success);
2645 // The first window gets cancel and the second gets down
2646 firstWindow->consumeMotionCancel();
2647 secondWindow->consumeMotionDown();
2648
2649 // Send up event to the second window
2650 NotifyMotionArgs upMotionArgs =
2651 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2652 ADISPLAY_ID_DEFAULT);
2653 mDispatcher->notifyMotion(&upMotionArgs);
2654 // The first window gets no events and the second+spy get up
2655 firstWindow->assertNoEvents();
2656 spyWindow->consumeMotionUp();
2657 secondWindow->consumeMotionUp();
2658}
2659
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002660TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002662
2663 PointF touchPoint = {10, 10};
2664
2665 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002666 sp<FakeWindowHandle> firstWindow =
2667 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002668 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002669 sp<FakeWindowHandle> secondWindow =
2670 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002671 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002672
2673 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002675
2676 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002677 NotifyMotionArgs downMotionArgs =
2678 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2679 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002680 mDispatcher->notifyMotion(&downMotionArgs);
2681 // Only the first window should get the down event
2682 firstWindow->consumeMotionDown();
2683 secondWindow->assertNoEvents();
2684
2685 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002686 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002687 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002688 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002689 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2690 // Only the first window should get the pointer down event
2691 firstWindow->consumeMotionPointerDown(1);
2692 secondWindow->assertNoEvents();
2693
2694 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002695 TransferFunction f = GetParam();
2696 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2697 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002698 // The first window gets cancel and the second gets down and pointer down
2699 firstWindow->consumeMotionCancel();
2700 secondWindow->consumeMotionDown();
2701 secondWindow->consumeMotionPointerDown(1);
2702
2703 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002704 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002705 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002706 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002707 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2708 // The first window gets nothing and the second gets pointer up
2709 firstWindow->assertNoEvents();
2710 secondWindow->consumeMotionPointerUp(1);
2711
2712 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002713 NotifyMotionArgs upMotionArgs =
2714 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2715 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002716 mDispatcher->notifyMotion(&upMotionArgs);
2717 // The first window gets nothing and the second gets up
2718 firstWindow->assertNoEvents();
2719 secondWindow->consumeMotionUp();
2720}
2721
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002722// For the cases of single pointer touch and two pointers non-split touch, the api's
2723// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2724// for the case where there are multiple pointers split across several windows.
2725INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2726 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002727 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2728 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002729 return dispatcher->transferTouch(destChannelToken,
2730 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002731 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002732 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2733 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002734 return dispatcher->transferTouchFocus(from, to,
2735 false /*isDragAndDrop*/);
2736 }));
2737
Svet Ganov5d3bc372020-01-26 23:11:07 -08002738TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002740
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002741 sp<FakeWindowHandle> firstWindow =
2742 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002743 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002744
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002745 sp<FakeWindowHandle> secondWindow =
2746 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002747 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002748
2749 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002751
2752 PointF pointInFirst = {300, 200};
2753 PointF pointInSecond = {300, 600};
2754
2755 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002756 NotifyMotionArgs firstDownMotionArgs =
2757 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2758 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002759 mDispatcher->notifyMotion(&firstDownMotionArgs);
2760 // Only the first window should get the down event
2761 firstWindow->consumeMotionDown();
2762 secondWindow->assertNoEvents();
2763
2764 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002765 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002766 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002767 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002768 mDispatcher->notifyMotion(&secondDownMotionArgs);
2769 // The first window gets a move and the second a down
2770 firstWindow->consumeMotionMove();
2771 secondWindow->consumeMotionDown();
2772
2773 // Transfer touch focus to the second window
2774 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2775 // The first window gets cancel and the new gets pointer down (it already saw down)
2776 firstWindow->consumeMotionCancel();
2777 secondWindow->consumeMotionPointerDown(1);
2778
2779 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002780 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002781 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002782 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002783 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2784 // The first window gets nothing and the second gets pointer up
2785 firstWindow->assertNoEvents();
2786 secondWindow->consumeMotionPointerUp(1);
2787
2788 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002789 NotifyMotionArgs upMotionArgs =
2790 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2791 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002792 mDispatcher->notifyMotion(&upMotionArgs);
2793 // The first window gets nothing and the second gets up
2794 firstWindow->assertNoEvents();
2795 secondWindow->consumeMotionUp();
2796}
2797
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002798// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2799// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2800// touch is not supported, so the touch should continue on those windows and the transferred-to
2801// window should get nothing.
2802TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2803 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2804
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002805 sp<FakeWindowHandle> firstWindow =
2806 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2807 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002808
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002809 sp<FakeWindowHandle> secondWindow =
2810 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2811 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002812
2813 // Add the windows to the dispatcher
2814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2815
2816 PointF pointInFirst = {300, 200};
2817 PointF pointInSecond = {300, 600};
2818
2819 // Send down to the first window
2820 NotifyMotionArgs firstDownMotionArgs =
2821 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2822 ADISPLAY_ID_DEFAULT, {pointInFirst});
2823 mDispatcher->notifyMotion(&firstDownMotionArgs);
2824 // Only the first window should get the down event
2825 firstWindow->consumeMotionDown();
2826 secondWindow->assertNoEvents();
2827
2828 // Send down to the second window
2829 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002830 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002831 {pointInFirst, pointInSecond});
2832 mDispatcher->notifyMotion(&secondDownMotionArgs);
2833 // The first window gets a move and the second a down
2834 firstWindow->consumeMotionMove();
2835 secondWindow->consumeMotionDown();
2836
2837 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002838 const bool transferred =
2839 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002840 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2841 ASSERT_FALSE(transferred);
2842 firstWindow->assertNoEvents();
2843 secondWindow->assertNoEvents();
2844
2845 // The rest of the dispatch should proceed as normal
2846 // Send pointer up to the second window
2847 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002848 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002849 {pointInFirst, pointInSecond});
2850 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2851 // The first window gets MOVE and the second gets pointer up
2852 firstWindow->consumeMotionMove();
2853 secondWindow->consumeMotionUp();
2854
2855 // Send up event to the first window
2856 NotifyMotionArgs upMotionArgs =
2857 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2858 ADISPLAY_ID_DEFAULT);
2859 mDispatcher->notifyMotion(&upMotionArgs);
2860 // The first window gets nothing and the second gets up
2861 firstWindow->consumeMotionUp();
2862 secondWindow->assertNoEvents();
2863}
2864
Arthur Hungabbb9d82021-09-01 14:52:30 +00002865// This case will create two windows and one mirrored window on the default display and mirror
2866// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2867// the windows info of second display before default display.
2868TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2869 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2870 sp<FakeWindowHandle> firstWindowInPrimary =
2871 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2872 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002873 sp<FakeWindowHandle> secondWindowInPrimary =
2874 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2875 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002876
2877 sp<FakeWindowHandle> mirrorWindowInPrimary =
2878 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2879 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002880
2881 sp<FakeWindowHandle> firstWindowInSecondary =
2882 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2883 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002884
2885 sp<FakeWindowHandle> secondWindowInSecondary =
2886 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2887 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002888
2889 // Update window info, let it find window handle of second display first.
2890 mDispatcher->setInputWindows(
2891 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2892 {ADISPLAY_ID_DEFAULT,
2893 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2894
2895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2897 {50, 50}))
2898 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2899
2900 // Window should receive motion event.
2901 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2902
2903 // Transfer touch focus
2904 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2905 secondWindowInPrimary->getToken()));
2906 // The first window gets cancel.
2907 firstWindowInPrimary->consumeMotionCancel();
2908 secondWindowInPrimary->consumeMotionDown();
2909
2910 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2911 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2912 ADISPLAY_ID_DEFAULT, {150, 50}))
2913 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2914 firstWindowInPrimary->assertNoEvents();
2915 secondWindowInPrimary->consumeMotionMove();
2916
2917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2918 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2919 {150, 50}))
2920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2921 firstWindowInPrimary->assertNoEvents();
2922 secondWindowInPrimary->consumeMotionUp();
2923}
2924
2925// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2926// 'transferTouch' api.
2927TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2928 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2929 sp<FakeWindowHandle> firstWindowInPrimary =
2930 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2931 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002932 sp<FakeWindowHandle> secondWindowInPrimary =
2933 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2934 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002935
2936 sp<FakeWindowHandle> mirrorWindowInPrimary =
2937 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2938 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002939
2940 sp<FakeWindowHandle> firstWindowInSecondary =
2941 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2942 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002943
2944 sp<FakeWindowHandle> secondWindowInSecondary =
2945 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2946 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002947
2948 // Update window info, let it find window handle of second display first.
2949 mDispatcher->setInputWindows(
2950 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2951 {ADISPLAY_ID_DEFAULT,
2952 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2953
2954 // Touch on second display.
2955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2956 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2957 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2958
2959 // Window should receive motion event.
2960 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2961
2962 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002963 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002964
2965 // The first window gets cancel.
2966 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2967 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2968
2969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2970 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2971 SECOND_DISPLAY_ID, {150, 50}))
2972 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2973 firstWindowInPrimary->assertNoEvents();
2974 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2975
2976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2977 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2979 firstWindowInPrimary->assertNoEvents();
2980 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2981}
2982
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002983TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002985 sp<FakeWindowHandle> window =
2986 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2987
Vishnu Nair47074b82020-08-14 11:54:47 -07002988 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002990 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002991
2992 window->consumeFocusEvent(true);
2993
2994 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2995 mDispatcher->notifyKey(&keyArgs);
2996
2997 // Window should receive key down event.
2998 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2999}
3000
3001TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003002 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003003 sp<FakeWindowHandle> window =
3004 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3005
Arthur Hung72d8dc32020-03-28 00:48:39 +00003006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007
3008 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3009 mDispatcher->notifyKey(&keyArgs);
3010 mDispatcher->waitForIdle();
3011
3012 window->assertNoEvents();
3013}
3014
3015// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3016TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003017 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003018 sp<FakeWindowHandle> window =
3019 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3020
Arthur Hung72d8dc32020-03-28 00:48:39 +00003021 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003022
3023 // Send key
3024 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3025 mDispatcher->notifyKey(&keyArgs);
3026 // Send motion
3027 NotifyMotionArgs motionArgs =
3028 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3029 ADISPLAY_ID_DEFAULT);
3030 mDispatcher->notifyMotion(&motionArgs);
3031
3032 // Window should receive only the motion event
3033 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3034 window->assertNoEvents(); // Key event or focus event will not be received
3035}
3036
arthurhungea3f4fc2020-12-21 23:18:53 +08003037TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3038 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3039
arthurhungea3f4fc2020-12-21 23:18:53 +08003040 sp<FakeWindowHandle> firstWindow =
3041 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3042 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003043
arthurhungea3f4fc2020-12-21 23:18:53 +08003044 sp<FakeWindowHandle> secondWindow =
3045 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3046 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003047
3048 // Add the windows to the dispatcher
3049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3050
3051 PointF pointInFirst = {300, 200};
3052 PointF pointInSecond = {300, 600};
3053
3054 // Send down to the first window
3055 NotifyMotionArgs firstDownMotionArgs =
3056 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3057 ADISPLAY_ID_DEFAULT, {pointInFirst});
3058 mDispatcher->notifyMotion(&firstDownMotionArgs);
3059 // Only the first window should get the down event
3060 firstWindow->consumeMotionDown();
3061 secondWindow->assertNoEvents();
3062
3063 // Send down to the second window
3064 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003065 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003066 {pointInFirst, pointInSecond});
3067 mDispatcher->notifyMotion(&secondDownMotionArgs);
3068 // The first window gets a move and the second a down
3069 firstWindow->consumeMotionMove();
3070 secondWindow->consumeMotionDown();
3071
3072 // Send pointer cancel to the second window
3073 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003074 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003075 {pointInFirst, pointInSecond});
3076 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3077 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3078 // The first window gets move and the second gets cancel.
3079 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3080 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3081
3082 // Send up event.
3083 NotifyMotionArgs upMotionArgs =
3084 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3085 ADISPLAY_ID_DEFAULT);
3086 mDispatcher->notifyMotion(&upMotionArgs);
3087 // The first window gets up and the second gets nothing.
3088 firstWindow->consumeMotionUp();
3089 secondWindow->assertNoEvents();
3090}
3091
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003092TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3093 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3094
3095 sp<FakeWindowHandle> window =
3096 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3098 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3099 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3100 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3101
3102 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3103 window->assertNoEvents();
3104 mDispatcher->waitForIdle();
3105}
3106
chaviwd1c23182019-12-20 18:44:56 -08003107class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003108public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003109 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003110 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003111 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003112 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003113 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003114 }
3115
chaviwd1c23182019-12-20 18:44:56 -08003116 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3117
3118 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3119 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3120 expectedDisplayId, expectedFlags);
3121 }
3122
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003123 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3124
3125 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3126
chaviwd1c23182019-12-20 18:44:56 -08003127 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3128 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3129 expectedDisplayId, expectedFlags);
3130 }
3131
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003132 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3133 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3134 expectedDisplayId, expectedFlags);
3135 }
3136
chaviwd1c23182019-12-20 18:44:56 -08003137 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3138 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3139 expectedDisplayId, expectedFlags);
3140 }
3141
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003142 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3143 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3144 expectedDisplayId, expectedFlags);
3145 }
3146
Arthur Hungfbfa5722021-11-16 02:45:54 +00003147 void consumeMotionPointerDown(int32_t pointerIdx) {
3148 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3149 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3150 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3151 0 /*expectedFlags*/);
3152 }
3153
Evan Rosky84f07f02021-04-16 10:42:42 -07003154 MotionEvent* consumeMotion() {
3155 InputEvent* event = mInputReceiver->consume();
3156 if (!event) {
3157 ADD_FAILURE() << "No event was produced";
3158 return nullptr;
3159 }
3160 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3161 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3162 return nullptr;
3163 }
3164 return static_cast<MotionEvent*>(event);
3165 }
3166
chaviwd1c23182019-12-20 18:44:56 -08003167 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3168
3169private:
3170 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003171};
3172
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003173using InputDispatcherMonitorTest = InputDispatcherTest;
3174
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003175/**
3176 * Two entities that receive touch: A window, and a global monitor.
3177 * The touch goes to the window, and then the window disappears.
3178 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3179 * for the monitor, as well.
3180 * 1. foregroundWindow
3181 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3182 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003183TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003184 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3185 sp<FakeWindowHandle> window =
3186 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3187
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003188 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003189
3190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3192 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3193 {100, 200}))
3194 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3195
3196 // Both the foreground window and the global monitor should receive the touch down
3197 window->consumeMotionDown();
3198 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3199
3200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3201 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3202 ADISPLAY_ID_DEFAULT, {110, 200}))
3203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3204
3205 window->consumeMotionMove();
3206 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3207
3208 // Now the foreground window goes away
3209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3210 window->consumeMotionCancel();
3211 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3212
3213 // If more events come in, there will be no more foreground window to send them to. This will
3214 // cause a cancel for the monitor, as well.
3215 ASSERT_EQ(InputEventInjectionResult::FAILED,
3216 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3217 ADISPLAY_ID_DEFAULT, {120, 200}))
3218 << "Injection should fail because the window was removed";
3219 window->assertNoEvents();
3220 // Global monitor now gets the cancel
3221 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3222}
3223
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003224TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003226 sp<FakeWindowHandle> window =
3227 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003229
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003230 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003231
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003233 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003234 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003235 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003236 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003237}
3238
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003239TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3240 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003241
Chris Yea209fde2020-07-22 13:54:51 -07003242 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003243 sp<FakeWindowHandle> window =
3244 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003246
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003248 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003249 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003250 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003251 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003252
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003253 // Pilfer pointers from the monitor.
3254 // This should not do anything and the window should continue to receive events.
3255 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003256
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003258 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3259 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003260 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003261
3262 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3263 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003264}
3265
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003266TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003267 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3268 sp<FakeWindowHandle> window =
3269 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3271 window->setWindowOffset(20, 40);
3272 window->setWindowTransform(0, 1, -1, 0);
3273
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003274 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003275
3276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3277 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3278 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3279 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3280 MotionEvent* event = monitor.consumeMotion();
3281 // Even though window has transform, gesture monitor must not.
3282 ASSERT_EQ(ui::Transform(), event->getTransform());
3283}
3284
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003285TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003286 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003287 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003288
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003289 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003290 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003291 << "Injection should fail if there is a monitor, but no touchable window";
3292 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003293}
3294
chaviw81e2bb92019-12-18 15:03:51 -08003295TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003296 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003297 sp<FakeWindowHandle> window =
3298 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3299
Arthur Hung72d8dc32020-03-28 00:48:39 +00003300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003301
3302 NotifyMotionArgs motionArgs =
3303 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3304 ADISPLAY_ID_DEFAULT);
3305
3306 mDispatcher->notifyMotion(&motionArgs);
3307 // Window should receive motion down event.
3308 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3309
3310 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003311 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003312 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3313 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3314 motionArgs.pointerCoords[0].getX() - 10);
3315
3316 mDispatcher->notifyMotion(&motionArgs);
3317 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3318 0 /*expectedFlags*/);
3319}
3320
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003321/**
3322 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3323 * the device default right away. In the test scenario, we check both the default value,
3324 * and the action of enabling / disabling.
3325 */
3326TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003328 sp<FakeWindowHandle> window =
3329 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003330 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003331
3332 // Set focused application.
3333 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003334 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003335
3336 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003338 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003339 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3340
3341 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003342 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003344 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3345
3346 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003347 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3348 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003349 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003350 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003352 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003353 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3354
3355 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003356 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003358 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3359
3360 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003361 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3362 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003363 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003364 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003366 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003367 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3368
3369 window->assertNoEvents();
3370}
3371
Gang Wange9087892020-01-07 12:17:14 -05003372TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003373 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003374 sp<FakeWindowHandle> window =
3375 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3376
3377 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003378 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003379
Arthur Hung72d8dc32020-03-28 00:48:39 +00003380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003381 setFocusedWindow(window);
3382
Gang Wange9087892020-01-07 12:17:14 -05003383 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3384
3385 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3386 mDispatcher->notifyKey(&keyArgs);
3387
3388 InputEvent* event = window->consume();
3389 ASSERT_NE(event, nullptr);
3390
3391 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3392 ASSERT_NE(verified, nullptr);
3393 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3394
3395 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3396 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3397 ASSERT_EQ(keyArgs.source, verified->source);
3398 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3399
3400 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3401
3402 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003403 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003404 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003405 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3406 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3407 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3408 ASSERT_EQ(0, verifiedKey.repeatCount);
3409}
3410
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003411TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003412 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003413 sp<FakeWindowHandle> window =
3414 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3415
3416 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3417
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003418 ui::Transform transform;
3419 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3420
3421 gui::DisplayInfo displayInfo;
3422 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3423 displayInfo.transform = transform;
3424
3425 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003426
3427 NotifyMotionArgs motionArgs =
3428 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3429 ADISPLAY_ID_DEFAULT);
3430 mDispatcher->notifyMotion(&motionArgs);
3431
3432 InputEvent* event = window->consume();
3433 ASSERT_NE(event, nullptr);
3434
3435 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3436 ASSERT_NE(verified, nullptr);
3437 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3438
3439 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3440 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3441 EXPECT_EQ(motionArgs.source, verified->source);
3442 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3443
3444 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3445
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003446 const vec2 rawXY =
3447 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3448 motionArgs.pointerCoords[0].getXYValue());
3449 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3450 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003451 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003452 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003453 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003454 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3455 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3456}
3457
chaviw09c8d2d2020-08-24 15:48:26 -07003458/**
3459 * Ensure that separate calls to sign the same data are generating the same key.
3460 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3461 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3462 * tests.
3463 */
3464TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3465 KeyEvent event = getTestKeyEvent();
3466 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3467
3468 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3469 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3470 ASSERT_EQ(hmac1, hmac2);
3471}
3472
3473/**
3474 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3475 */
3476TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3477 KeyEvent event = getTestKeyEvent();
3478 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3479 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3480
3481 verifiedEvent.deviceId += 1;
3482 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3483
3484 verifiedEvent.source += 1;
3485 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3486
3487 verifiedEvent.eventTimeNanos += 1;
3488 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3489
3490 verifiedEvent.displayId += 1;
3491 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3492
3493 verifiedEvent.action += 1;
3494 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3495
3496 verifiedEvent.downTimeNanos += 1;
3497 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3498
3499 verifiedEvent.flags += 1;
3500 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3501
3502 verifiedEvent.keyCode += 1;
3503 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3504
3505 verifiedEvent.scanCode += 1;
3506 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3507
3508 verifiedEvent.metaState += 1;
3509 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3510
3511 verifiedEvent.repeatCount += 1;
3512 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3513}
3514
Vishnu Nair958da932020-08-21 17:12:37 -07003515TEST_F(InputDispatcherTest, SetFocusedWindow) {
3516 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3517 sp<FakeWindowHandle> windowTop =
3518 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3519 sp<FakeWindowHandle> windowSecond =
3520 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3521 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3522
3523 // Top window is also focusable but is not granted focus.
3524 windowTop->setFocusable(true);
3525 windowSecond->setFocusable(true);
3526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3527 setFocusedWindow(windowSecond);
3528
3529 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3531 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003532
3533 // Focused window should receive event.
3534 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3535 windowTop->assertNoEvents();
3536}
3537
3538TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3540 sp<FakeWindowHandle> window =
3541 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3542 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3543
3544 window->setFocusable(true);
3545 // Release channel for window is no longer valid.
3546 window->releaseChannel();
3547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3548 setFocusedWindow(window);
3549
3550 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003551 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3552 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003553
3554 // window channel is invalid, so it should not receive any input event.
3555 window->assertNoEvents();
3556}
3557
3558TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3559 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3560 sp<FakeWindowHandle> window =
3561 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003562 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003563 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3564
Vishnu Nair958da932020-08-21 17:12:37 -07003565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3566 setFocusedWindow(window);
3567
3568 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003569 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3570 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003571
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003572 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003573 window->assertNoEvents();
3574}
3575
3576TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3577 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3578 sp<FakeWindowHandle> windowTop =
3579 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3580 sp<FakeWindowHandle> windowSecond =
3581 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3582 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3583
3584 windowTop->setFocusable(true);
3585 windowSecond->setFocusable(true);
3586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3587 setFocusedWindow(windowTop);
3588 windowTop->consumeFocusEvent(true);
3589
3590 setFocusedWindow(windowSecond, windowTop);
3591 windowSecond->consumeFocusEvent(true);
3592 windowTop->consumeFocusEvent(false);
3593
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3595 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003596
3597 // Focused window should receive event.
3598 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3599}
3600
3601TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3603 sp<FakeWindowHandle> windowTop =
3604 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3605 sp<FakeWindowHandle> windowSecond =
3606 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3607 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3608
3609 windowTop->setFocusable(true);
3610 windowSecond->setFocusable(true);
3611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3612 setFocusedWindow(windowSecond, windowTop);
3613
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3615 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003616
3617 // Event should be dropped.
3618 windowTop->assertNoEvents();
3619 windowSecond->assertNoEvents();
3620}
3621
3622TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3624 sp<FakeWindowHandle> window =
3625 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3626 sp<FakeWindowHandle> previousFocusedWindow =
3627 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3628 ADISPLAY_ID_DEFAULT);
3629 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3630
3631 window->setFocusable(true);
3632 previousFocusedWindow->setFocusable(true);
3633 window->setVisible(false);
3634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3635 setFocusedWindow(previousFocusedWindow);
3636 previousFocusedWindow->consumeFocusEvent(true);
3637
3638 // Requesting focus on invisible window takes focus from currently focused window.
3639 setFocusedWindow(window);
3640 previousFocusedWindow->consumeFocusEvent(false);
3641
3642 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003644 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003645 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003646
3647 // Window does not get focus event or key down.
3648 window->assertNoEvents();
3649
3650 // Window becomes visible.
3651 window->setVisible(true);
3652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3653
3654 // Window receives focus event.
3655 window->consumeFocusEvent(true);
3656 // Focused window receives key down.
3657 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3658}
3659
Vishnu Nair599f1412021-06-21 10:39:58 -07003660TEST_F(InputDispatcherTest, DisplayRemoved) {
3661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3662 sp<FakeWindowHandle> window =
3663 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3664 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3665
3666 // window is granted focus.
3667 window->setFocusable(true);
3668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3669 setFocusedWindow(window);
3670 window->consumeFocusEvent(true);
3671
3672 // When a display is removed window loses focus.
3673 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3674 window->consumeFocusEvent(false);
3675}
3676
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003677/**
3678 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3679 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3680 * of the 'slipperyEnterWindow'.
3681 *
3682 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3683 * a way so that the touched location is no longer covered by the top window.
3684 *
3685 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3686 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3687 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3688 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3689 * with ACTION_DOWN).
3690 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3691 * window moved itself away from the touched location and had Flag::SLIPPERY.
3692 *
3693 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3694 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3695 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3696 *
3697 * In this test, we ensure that the event received by the bottom window has
3698 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3699 */
3700TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00003701 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3702 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003703
3704 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3705 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3706
3707 sp<FakeWindowHandle> slipperyExitWindow =
3708 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003709 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003710 // Make sure this one overlaps the bottom window
3711 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3712 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3713 // one. Windows with the same owner are not considered to be occluding each other.
3714 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3715
3716 sp<FakeWindowHandle> slipperyEnterWindow =
3717 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3718 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3719
3720 mDispatcher->setInputWindows(
3721 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3722
3723 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3724 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3725 ADISPLAY_ID_DEFAULT, {{50, 50}});
3726 mDispatcher->notifyMotion(&args);
3727 slipperyExitWindow->consumeMotionDown();
3728 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3729 mDispatcher->setInputWindows(
3730 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3731
3732 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3733 ADISPLAY_ID_DEFAULT, {{51, 51}});
3734 mDispatcher->notifyMotion(&args);
3735
3736 slipperyExitWindow->consumeMotionCancel();
3737
3738 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3739 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3740}
3741
Garfield Tan1c7bc862020-01-28 13:24:04 -08003742class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3743protected:
3744 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3745 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3746
Chris Yea209fde2020-07-22 13:54:51 -07003747 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003748 sp<FakeWindowHandle> mWindow;
3749
3750 virtual void SetUp() override {
3751 mFakePolicy = new FakeInputDispatcherPolicy();
3752 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003753 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003754 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3755 ASSERT_EQ(OK, mDispatcher->start());
3756
3757 setUpWindow();
3758 }
3759
3760 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003761 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003762 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3763
Vishnu Nair47074b82020-08-14 11:54:47 -07003764 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003766 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003767 mWindow->consumeFocusEvent(true);
3768 }
3769
Chris Ye2ad95392020-09-01 13:44:44 -07003770 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003771 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003772 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003773 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3774 mDispatcher->notifyKey(&keyArgs);
3775
3776 // Window should receive key down event.
3777 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3778 }
3779
3780 void expectKeyRepeatOnce(int32_t repeatCount) {
3781 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3782 InputEvent* repeatEvent = mWindow->consume();
3783 ASSERT_NE(nullptr, repeatEvent);
3784
3785 uint32_t eventType = repeatEvent->getType();
3786 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3787
3788 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3789 uint32_t eventAction = repeatKeyEvent->getAction();
3790 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3791 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3792 }
3793
Chris Ye2ad95392020-09-01 13:44:44 -07003794 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003795 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003796 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003797 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3798 mDispatcher->notifyKey(&keyArgs);
3799
3800 // Window should receive key down event.
3801 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3802 0 /*expectedFlags*/);
3803 }
3804};
3805
3806TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003807 sendAndConsumeKeyDown(1 /* deviceId */);
3808 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3809 expectKeyRepeatOnce(repeatCount);
3810 }
3811}
3812
3813TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3814 sendAndConsumeKeyDown(1 /* deviceId */);
3815 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3816 expectKeyRepeatOnce(repeatCount);
3817 }
3818 sendAndConsumeKeyDown(2 /* deviceId */);
3819 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003820 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3821 expectKeyRepeatOnce(repeatCount);
3822 }
3823}
3824
3825TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003826 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003827 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003828 sendAndConsumeKeyUp(1 /* deviceId */);
3829 mWindow->assertNoEvents();
3830}
3831
3832TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3833 sendAndConsumeKeyDown(1 /* deviceId */);
3834 expectKeyRepeatOnce(1 /*repeatCount*/);
3835 sendAndConsumeKeyDown(2 /* deviceId */);
3836 expectKeyRepeatOnce(1 /*repeatCount*/);
3837 // Stale key up from device 1.
3838 sendAndConsumeKeyUp(1 /* deviceId */);
3839 // Device 2 is still down, keep repeating
3840 expectKeyRepeatOnce(2 /*repeatCount*/);
3841 expectKeyRepeatOnce(3 /*repeatCount*/);
3842 // Device 2 key up
3843 sendAndConsumeKeyUp(2 /* deviceId */);
3844 mWindow->assertNoEvents();
3845}
3846
3847TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3848 sendAndConsumeKeyDown(1 /* deviceId */);
3849 expectKeyRepeatOnce(1 /*repeatCount*/);
3850 sendAndConsumeKeyDown(2 /* deviceId */);
3851 expectKeyRepeatOnce(1 /*repeatCount*/);
3852 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3853 sendAndConsumeKeyUp(2 /* deviceId */);
3854 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003855 mWindow->assertNoEvents();
3856}
3857
liushenxiang42232912021-05-21 20:24:09 +08003858TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3859 sendAndConsumeKeyDown(DEVICE_ID);
3860 expectKeyRepeatOnce(1 /*repeatCount*/);
3861 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3862 mDispatcher->notifyDeviceReset(&args);
3863 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3864 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3865 mWindow->assertNoEvents();
3866}
3867
Garfield Tan1c7bc862020-01-28 13:24:04 -08003868TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003869 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003870 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3871 InputEvent* repeatEvent = mWindow->consume();
3872 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3873 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3874 IdGenerator::getSource(repeatEvent->getId()));
3875 }
3876}
3877
3878TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003879 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003880
3881 std::unordered_set<int32_t> idSet;
3882 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3883 InputEvent* repeatEvent = mWindow->consume();
3884 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3885 int32_t id = repeatEvent->getId();
3886 EXPECT_EQ(idSet.end(), idSet.find(id));
3887 idSet.insert(id);
3888 }
3889}
3890
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003891/* Test InputDispatcher for MultiDisplay */
3892class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3893public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003894 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003895 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003896
Chris Yea209fde2020-07-22 13:54:51 -07003897 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003898 windowInPrimary =
3899 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003900
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003901 // Set focus window for primary display, but focused display would be second one.
3902 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003903 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003905 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003906 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003907
Chris Yea209fde2020-07-22 13:54:51 -07003908 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003909 windowInSecondary =
3910 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003911 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003912 // Set focus display to second one.
3913 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3914 // Set focus window for second display.
3915 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003916 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003917 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003918 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003919 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003920 }
3921
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003922 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003923 InputDispatcherTest::TearDown();
3924
Chris Yea209fde2020-07-22 13:54:51 -07003925 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003926 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003927 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003928 windowInSecondary.clear();
3929 }
3930
3931protected:
Chris Yea209fde2020-07-22 13:54:51 -07003932 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003933 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003934 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003935 sp<FakeWindowHandle> windowInSecondary;
3936};
3937
3938TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3939 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3941 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3942 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003943 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003944 windowInSecondary->assertNoEvents();
3945
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003946 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3948 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003950 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003951 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003952}
3953
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003954TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003955 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3957 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003958 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003959 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003960 windowInSecondary->assertNoEvents();
3961
3962 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003964 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003965 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003966 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003967
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003968 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003969 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003970
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003971 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003972 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3973 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003974
3975 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003976 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003977 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003978 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003979 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003980 windowInSecondary->assertNoEvents();
3981}
3982
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003983// Test per-display input monitors for motion event.
3984TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003985 FakeMonitorReceiver monitorInPrimary =
3986 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3987 FakeMonitorReceiver monitorInSecondary =
3988 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003989
3990 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3992 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003994 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003995 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003996 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003997 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003998
3999 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4001 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004003 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004004 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004005 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004006 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004007
4008 // Test inject a non-pointer motion event.
4009 // If specific a display, it will dispatch to the focused window of particular display,
4010 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4012 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4013 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004014 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004015 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004016 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004017 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004018}
4019
4020// Test per-display input monitors for key event.
4021TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004022 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004023 FakeMonitorReceiver monitorInPrimary =
4024 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4025 FakeMonitorReceiver monitorInSecondary =
4026 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004027
4028 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4030 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004031 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004032 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004033 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004034 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004035}
4036
Vishnu Nair958da932020-08-21 17:12:37 -07004037TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4038 sp<FakeWindowHandle> secondWindowInPrimary =
4039 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
4040 secondWindowInPrimary->setFocusable(true);
4041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4042 setFocusedWindow(secondWindowInPrimary);
4043 windowInPrimary->consumeFocusEvent(false);
4044 secondWindowInPrimary->consumeFocusEvent(true);
4045
4046 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4048 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004049 windowInPrimary->assertNoEvents();
4050 windowInSecondary->assertNoEvents();
4051 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4052}
4053
Arthur Hungdfd528e2021-12-08 13:23:04 +00004054TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4055 FakeMonitorReceiver monitorInPrimary =
4056 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4057 FakeMonitorReceiver monitorInSecondary =
4058 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4059
4060 // Test touch down on primary display.
4061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4062 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4064 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4065 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4066
4067 // Test touch down on second display.
4068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4069 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4070 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4071 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4072 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4073
4074 // Trigger cancel touch.
4075 mDispatcher->cancelCurrentTouch();
4076 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4077 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4078 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4079 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4080
4081 // Test inject a move motion event, no window/monitor should receive the event.
4082 ASSERT_EQ(InputEventInjectionResult::FAILED,
4083 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4084 ADISPLAY_ID_DEFAULT, {110, 200}))
4085 << "Inject motion event should return InputEventInjectionResult::FAILED";
4086 windowInPrimary->assertNoEvents();
4087 monitorInPrimary.assertNoEvents();
4088
4089 ASSERT_EQ(InputEventInjectionResult::FAILED,
4090 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4091 SECOND_DISPLAY_ID, {110, 200}))
4092 << "Inject motion event should return InputEventInjectionResult::FAILED";
4093 windowInSecondary->assertNoEvents();
4094 monitorInSecondary.assertNoEvents();
4095}
4096
Jackal Guof9696682018-10-05 12:23:23 +08004097class InputFilterTest : public InputDispatcherTest {
4098protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004099 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4100 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004101 NotifyMotionArgs motionArgs;
4102
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004103 motionArgs =
4104 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004105 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004106 motionArgs =
4107 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004108 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004109 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004110 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004111 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4112 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004113 } else {
4114 mFakePolicy->assertFilterInputEventWasNotCalled();
4115 }
4116 }
4117
4118 void testNotifyKey(bool expectToBeFiltered) {
4119 NotifyKeyArgs keyArgs;
4120
4121 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4122 mDispatcher->notifyKey(&keyArgs);
4123 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4124 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004125 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004126
4127 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004128 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004129 } else {
4130 mFakePolicy->assertFilterInputEventWasNotCalled();
4131 }
4132 }
4133};
4134
4135// Test InputFilter for MotionEvent
4136TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4137 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4138 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4139 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4140
4141 // Enable InputFilter
4142 mDispatcher->setInputFilterEnabled(true);
4143 // Test touch on both primary and second display, and check if both events are filtered.
4144 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4145 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4146
4147 // Disable InputFilter
4148 mDispatcher->setInputFilterEnabled(false);
4149 // Test touch on both primary and second display, and check if both events aren't filtered.
4150 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4151 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4152}
4153
4154// Test InputFilter for KeyEvent
4155TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4156 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4157 testNotifyKey(/*expectToBeFiltered*/ false);
4158
4159 // Enable InputFilter
4160 mDispatcher->setInputFilterEnabled(true);
4161 // Send a key event, and check if it is filtered.
4162 testNotifyKey(/*expectToBeFiltered*/ true);
4163
4164 // Disable InputFilter
4165 mDispatcher->setInputFilterEnabled(false);
4166 // Send a key event, and check if it isn't filtered.
4167 testNotifyKey(/*expectToBeFiltered*/ false);
4168}
4169
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004170// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4171// logical display coordinate space.
4172TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4173 ui::Transform firstDisplayTransform;
4174 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4175 ui::Transform secondDisplayTransform;
4176 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4177
4178 std::vector<gui::DisplayInfo> displayInfos(2);
4179 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4180 displayInfos[0].transform = firstDisplayTransform;
4181 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4182 displayInfos[1].transform = secondDisplayTransform;
4183
4184 mDispatcher->onWindowInfosChanged({}, displayInfos);
4185
4186 // Enable InputFilter
4187 mDispatcher->setInputFilterEnabled(true);
4188
4189 // Ensure the correct transforms are used for the displays.
4190 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4191 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4192}
4193
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4195protected:
4196 virtual void SetUp() override {
4197 InputDispatcherTest::SetUp();
4198
4199 /**
4200 * We don't need to enable input filter to test the injected event policy, but we enabled it
4201 * here to make the tests more realistic, since this policy only matters when inputfilter is
4202 * on.
4203 */
4204 mDispatcher->setInputFilterEnabled(true);
4205
4206 std::shared_ptr<InputApplicationHandle> application =
4207 std::make_shared<FakeApplicationHandle>();
4208 mWindow =
4209 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4210
4211 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4212 mWindow->setFocusable(true);
4213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4214 setFocusedWindow(mWindow);
4215 mWindow->consumeFocusEvent(true);
4216 }
4217
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004218 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4219 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 KeyEvent event;
4221
4222 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4223 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4224 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4225 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4226 const int32_t additionalPolicyFlags =
4227 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004229 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4231 policyFlags | additionalPolicyFlags));
4232
4233 InputEvent* received = mWindow->consume();
4234 ASSERT_NE(nullptr, received);
4235 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004236 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4237 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4238 ASSERT_EQ(flags, keyEvent.getFlags());
4239 }
4240
4241 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4242 int32_t flags) {
4243 MotionEvent event;
4244 PointerProperties pointerProperties[1];
4245 PointerCoords pointerCoords[1];
4246 pointerProperties[0].clear();
4247 pointerProperties[0].id = 0;
4248 pointerCoords[0].clear();
4249 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4250 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4251
4252 ui::Transform identityTransform;
4253 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4254 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4255 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4256 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4257 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004258 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004259 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004260 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4261
4262 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004264 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004265 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4266 policyFlags | additionalPolicyFlags));
4267
4268 InputEvent* received = mWindow->consume();
4269 ASSERT_NE(nullptr, received);
4270 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4271 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4272 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4273 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004274 }
4275
4276private:
4277 sp<FakeWindowHandle> mWindow;
4278};
4279
4280TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004281 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4282 // filter. Without it, the event will no different from a regularly injected event, and the
4283 // injected device id will be overwritten.
4284 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4285 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286}
4287
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004288TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004289 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004290 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4291 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4292}
4293
4294TEST_F(InputFilterInjectionPolicyTest,
4295 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4296 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4297 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4298 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299}
4300
4301TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4302 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004303 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004304}
4305
chaviwfd6d3512019-03-25 13:23:49 -07004306class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004307 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004308 InputDispatcherTest::SetUp();
4309
Chris Yea209fde2020-07-22 13:54:51 -07004310 std::shared_ptr<FakeApplicationHandle> application =
4311 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004312 mUnfocusedWindow =
4313 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004314 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004315
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004316 mFocusedWindow =
4317 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4318 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004319
4320 // Set focused application.
4321 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004322 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004323
4324 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004326 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004327 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004328 }
4329
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004330 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004331 InputDispatcherTest::TearDown();
4332
4333 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004334 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004335 }
4336
4337protected:
4338 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004339 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004340 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004341};
4342
4343// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4344// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4345// the onPointerDownOutsideFocus callback.
4346TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004348 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4349 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004350 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004351 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004352
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004353 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004354 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4355}
4356
4357// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4358// DOWN on the window that doesn't have focus. Ensure no window received the
4359// onPointerDownOutsideFocus callback.
4360TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004362 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004364 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004365
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004366 ASSERT_TRUE(mDispatcher->waitForIdle());
4367 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004368}
4369
4370// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4371// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4372TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4374 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004376 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004377
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004378 ASSERT_TRUE(mDispatcher->waitForIdle());
4379 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004380}
4381
4382// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4383// DOWN on the window that already has focus. Ensure no window received the
4384// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004385TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004387 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004388 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004389 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004390 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004391
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004392 ASSERT_TRUE(mDispatcher->waitForIdle());
4393 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004394}
4395
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004396// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4397// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4398TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4399 const MotionEvent event =
4400 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4401 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4402 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4403 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4404 .build();
4405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4407 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4408
4409 ASSERT_TRUE(mDispatcher->waitForIdle());
4410 mFakePolicy->assertOnPointerDownWasNotCalled();
4411 // Ensure that the unfocused window did not receive any FOCUS events.
4412 mUnfocusedWindow->assertNoEvents();
4413}
4414
chaviwaf87b3e2019-10-01 16:59:28 -07004415// These tests ensures we can send touch events to a single client when there are multiple input
4416// windows that point to the same client token.
4417class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4418 virtual void SetUp() override {
4419 InputDispatcherTest::SetUp();
4420
Chris Yea209fde2020-07-22 13:54:51 -07004421 std::shared_ptr<FakeApplicationHandle> application =
4422 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004423 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4424 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004425 mWindow1->setFrame(Rect(0, 0, 100, 100));
4426
4427 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4428 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004429 mWindow2->setFrame(Rect(100, 100, 200, 200));
4430
Arthur Hung72d8dc32020-03-28 00:48:39 +00004431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004432 }
4433
4434protected:
4435 sp<FakeWindowHandle> mWindow1;
4436 sp<FakeWindowHandle> mWindow2;
4437
4438 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004439 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004440 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4441 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004442 }
4443
4444 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4445 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004446 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004447 InputEvent* event = window->consume();
4448
4449 ASSERT_NE(nullptr, event) << name.c_str()
4450 << ": consumer should have returned non-NULL event.";
4451
4452 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4453 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4454 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4455
4456 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004457 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004458
4459 for (size_t i = 0; i < points.size(); i++) {
4460 float expectedX = points[i].x;
4461 float expectedY = points[i].y;
4462
4463 EXPECT_EQ(expectedX, motionEvent.getX(i))
4464 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4465 << ", got " << motionEvent.getX(i);
4466 EXPECT_EQ(expectedY, motionEvent.getY(i))
4467 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4468 << ", got " << motionEvent.getY(i);
4469 }
4470 }
chaviw9eaa22c2020-07-01 16:21:27 -07004471
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004472 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004473 std::vector<PointF> expectedPoints) {
4474 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4475 ADISPLAY_ID_DEFAULT, touchedPoints);
4476 mDispatcher->notifyMotion(&motionArgs);
4477
4478 // Always consume from window1 since it's the window that has the InputReceiver
4479 consumeMotionEvent(mWindow1, action, expectedPoints);
4480 }
chaviwaf87b3e2019-10-01 16:59:28 -07004481};
4482
4483TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4484 // Touch Window 1
4485 PointF touchedPoint = {10, 10};
4486 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004487 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004488
4489 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004490 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004491
4492 // Touch Window 2
4493 touchedPoint = {150, 150};
4494 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004495 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004496}
4497
chaviw9eaa22c2020-07-01 16:21:27 -07004498TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4499 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004500 mWindow2->setWindowScale(0.5f, 0.5f);
4501
4502 // Touch Window 1
4503 PointF touchedPoint = {10, 10};
4504 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004505 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004506 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004507 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004508
4509 // Touch Window 2
4510 touchedPoint = {150, 150};
4511 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004512 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4513 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004514
chaviw9eaa22c2020-07-01 16:21:27 -07004515 // Update the transform so rotation is set
4516 mWindow2->setWindowTransform(0, -1, 1, 0);
4517 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4518 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004519}
4520
chaviw9eaa22c2020-07-01 16:21:27 -07004521TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004522 mWindow2->setWindowScale(0.5f, 0.5f);
4523
4524 // Touch Window 1
4525 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4526 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004527 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004528
4529 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004530 touchedPoints.push_back(PointF{150, 150});
4531 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004532 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004533
chaviw9eaa22c2020-07-01 16:21:27 -07004534 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004535 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004536 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004537
chaviw9eaa22c2020-07-01 16:21:27 -07004538 // Update the transform so rotation is set for Window 2
4539 mWindow2->setWindowTransform(0, -1, 1, 0);
4540 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004541 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004542}
4543
chaviw9eaa22c2020-07-01 16:21:27 -07004544TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004545 mWindow2->setWindowScale(0.5f, 0.5f);
4546
4547 // Touch Window 1
4548 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4549 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004550 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004551
4552 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004553 touchedPoints.push_back(PointF{150, 150});
4554 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004555
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004556 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004557
4558 // Move both windows
4559 touchedPoints = {{20, 20}, {175, 175}};
4560 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4561 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4562
chaviw9eaa22c2020-07-01 16:21:27 -07004563 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004564
chaviw9eaa22c2020-07-01 16:21:27 -07004565 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004566 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004567 expectedPoints.pop_back();
4568
4569 // Touch Window 2
4570 mWindow2->setWindowTransform(0, -1, 1, 0);
4571 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004572 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004573
4574 // Move both windows
4575 touchedPoints = {{20, 20}, {175, 175}};
4576 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4577 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4578
4579 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004580}
4581
4582TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4583 mWindow1->setWindowScale(0.5f, 0.5f);
4584
4585 // Touch Window 1
4586 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4587 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004588 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004589
4590 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004591 touchedPoints.push_back(PointF{150, 150});
4592 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004593
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004594 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004595
4596 // Move both windows
4597 touchedPoints = {{20, 20}, {175, 175}};
4598 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4599 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4600
chaviw9eaa22c2020-07-01 16:21:27 -07004601 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004602}
4603
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004604class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4605 virtual void SetUp() override {
4606 InputDispatcherTest::SetUp();
4607
Chris Yea209fde2020-07-22 13:54:51 -07004608 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609 mApplication->setDispatchingTimeout(20ms);
4610 mWindow =
4611 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4612 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004613 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004614 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004615
4616 // Set focused application.
4617 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4618
4619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004620 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004621 mWindow->consumeFocusEvent(true);
4622 }
4623
4624 virtual void TearDown() override {
4625 InputDispatcherTest::TearDown();
4626 mWindow.clear();
4627 }
4628
4629protected:
Chris Yea209fde2020-07-22 13:54:51 -07004630 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004631 sp<FakeWindowHandle> mWindow;
4632 static constexpr PointF WINDOW_LOCATION = {20, 20};
4633
4634 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004636 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4637 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004639 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4640 WINDOW_LOCATION));
4641 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004642
4643 sp<FakeWindowHandle> addSpyWindow() {
4644 sp<FakeWindowHandle> spy =
4645 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4646 spy->setTrustedOverlay(true);
4647 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004648 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004649 spy->setDispatchingTimeout(30ms);
4650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4651 return spy;
4652 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004653};
4654
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655// Send a tap and respond, which should not cause an ANR.
4656TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4657 tapOnWindow();
4658 mWindow->consumeMotionDown();
4659 mWindow->consumeMotionUp();
4660 ASSERT_TRUE(mDispatcher->waitForIdle());
4661 mFakePolicy->assertNotifyAnrWasNotCalled();
4662}
4663
4664// Send a regular key and respond, which should not cause an ANR.
4665TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004667 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4668 ASSERT_TRUE(mDispatcher->waitForIdle());
4669 mFakePolicy->assertNotifyAnrWasNotCalled();
4670}
4671
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004672TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4673 mWindow->setFocusable(false);
4674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4675 mWindow->consumeFocusEvent(false);
4676
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004677 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004678 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004679 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4680 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004682 // Key will not go to window because we have no focused window.
4683 // The 'no focused window' ANR timer should start instead.
4684
4685 // Now, the focused application goes away.
4686 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4687 // The key should get dropped and there should be no ANR.
4688
4689 ASSERT_TRUE(mDispatcher->waitForIdle());
4690 mFakePolicy->assertNotifyAnrWasNotCalled();
4691}
4692
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004693// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4695// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004696TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4699 WINDOW_LOCATION));
4700
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004701 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4702 ASSERT_TRUE(sequenceNum);
4703 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004704 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004706 mWindow->finishEvent(*sequenceNum);
4707 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4708 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004709 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004710 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004711}
4712
4713// Send a key to the app and have the app not respond right away.
4714TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4715 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004717 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4718 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004719 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004720 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004721 ASSERT_TRUE(mDispatcher->waitForIdle());
4722}
4723
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724// We have a focused application, but no focused window
4725TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004726 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4728 mWindow->consumeFocusEvent(false);
4729
4730 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004732 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4733 WINDOW_LOCATION));
4734 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4735 mDispatcher->waitForIdle();
4736 mFakePolicy->assertNotifyAnrWasNotCalled();
4737
4738 // Once a focused event arrives, we get an ANR for this application
4739 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4740 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004743 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004744 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004746 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747 ASSERT_TRUE(mDispatcher->waitForIdle());
4748}
4749
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004750/**
4751 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4752 * there will not be an ANR.
4753 */
4754TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4755 mWindow->setFocusable(false);
4756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4757 mWindow->consumeFocusEvent(false);
4758
4759 KeyEvent event;
4760 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4761 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4762
4763 // Define a valid key down event that is stale (too old).
4764 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4765 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4766 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4767
4768 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4769
4770 InputEventInjectionResult result =
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004771 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004772 InputEventInjectionSync::WAIT_FOR_RESULT,
4773 INJECT_EVENT_TIMEOUT, policyFlags);
4774 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4775 << "Injection should fail because the event is stale";
4776
4777 ASSERT_TRUE(mDispatcher->waitForIdle());
4778 mFakePolicy->assertNotifyAnrWasNotCalled();
4779 mWindow->assertNoEvents();
4780}
4781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004782// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004783// Make sure that we don't notify policy twice about the same ANR.
4784TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004785 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4787 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788
4789 // Once a focused event arrives, we get an ANR for this application
4790 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4791 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004792 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004794 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004795 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796 const std::chrono::duration appTimeout =
4797 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004798 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004800 std::this_thread::sleep_for(appTimeout);
4801 // ANR should not be raised again. It is up to policy to do that if it desires.
4802 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004804 // If we now get a focused window, the ANR should stop, but the policy handles that via
4805 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 ASSERT_TRUE(mDispatcher->waitForIdle());
4807}
4808
4809// We have a focused application, but no focused window
4810TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004811 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4813 mWindow->consumeFocusEvent(false);
4814
4815 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004818 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4819 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820
4821 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004822 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823
4824 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826 ASSERT_TRUE(mDispatcher->waitForIdle());
4827 mWindow->assertNoEvents();
4828}
4829
4830/**
4831 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4832 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4833 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4834 * the ANR mechanism should still work.
4835 *
4836 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4837 * DOWN event, while not responding on the second one.
4838 */
4839TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4840 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4841 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4842 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4843 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4844 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004845 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846
4847 // Now send ACTION_UP, with identical timestamp
4848 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4849 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4850 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4851 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853
4854 // We have now sent down and up. Let's consume first event and then ANR on the second.
4855 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4856 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004857 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858}
4859
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004860// A spy window can receive an ANR
4861TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4862 sp<FakeWindowHandle> spy = addSpyWindow();
4863
4864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4865 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4866 WINDOW_LOCATION));
4867 mWindow->consumeMotionDown();
4868
4869 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4870 ASSERT_TRUE(sequenceNum);
4871 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004872 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004873
4874 spy->finishEvent(*sequenceNum);
4875 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4876 0 /*flags*/);
4877 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004878 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004879}
4880
4881// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004883TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4884 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4887 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890
4891 // Stuck on the ACTION_UP
4892 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004893 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004895 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004897 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4898 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899
4900 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4901 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004902 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004904 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905}
4906
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004907// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004908// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004909TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4910 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911
4912 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004913 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4914 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004915
4916 mWindow->consumeMotionDown();
4917 // Stuck on the ACTION_UP
4918 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004919 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004921 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004923 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4924 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925
4926 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
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();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004930 spy->assertNoEvents();
4931}
4932
4933TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4934 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4935
4936 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4937
4938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4940 WINDOW_LOCATION));
4941
4942 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4943 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4944 ASSERT_TRUE(consumeSeq);
4945
Prabir Pradhanedd96402022-02-15 01:46:16 -08004946 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004947
4948 monitor.finishEvent(*consumeSeq);
4949 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4950
4951 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004952 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004953}
4954
4955// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4956// process events, you don't get an anr. When the window later becomes unresponsive again, you
4957// get an ANR again.
4958// 1. tap -> block on ACTION_UP -> receive ANR
4959// 2. consume all pending events (= queue becomes healthy again)
4960// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4961TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4962 tapOnWindow();
4963
4964 mWindow->consumeMotionDown();
4965 // Block on ACTION_UP
4966 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004967 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004968 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4969 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004970 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971 mWindow->assertNoEvents();
4972
4973 tapOnWindow();
4974 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004975 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976 mWindow->consumeMotionUp();
4977
4978 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004979 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004980 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 mWindow->assertNoEvents();
4982}
4983
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004984// If a connection remains unresponsive for a while, make sure policy is only notified once about
4985// it.
4986TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4989 WINDOW_LOCATION));
4990
4991 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004992 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004993 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004994 // 'notifyConnectionUnresponsive' should only be called once per connection
4995 mFakePolicy->assertNotifyAnrWasNotCalled();
4996 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004997 mWindow->consumeMotionDown();
4998 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4999 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5000 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005001 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005002 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005003 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004}
5005
5006/**
5007 * If a window is processing a motion event, and then a key event comes in, the key event should
5008 * not to to the focused window until the motion is processed.
5009 *
5010 * Warning!!!
5011 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5012 * and the injection timeout that we specify when injecting the key.
5013 * We must have the injection timeout (10ms) be smaller than
5014 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5015 *
5016 * If that value changes, this test should also change.
5017 */
5018TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5019 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5021
5022 tapOnWindow();
5023 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5024 ASSERT_TRUE(downSequenceNum);
5025 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5026 ASSERT_TRUE(upSequenceNum);
5027 // Don't finish the events yet, and send a key
5028 // Injection will "succeed" because we will eventually give up and send the key to the focused
5029 // window even if motions are still being processed. But because the injection timeout is short,
5030 // we will receive INJECTION_TIMED_OUT as the result.
5031
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005032 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005033 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005034 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5035 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005036 // Key will not be sent to the window, yet, because the window is still processing events
5037 // and the key remains pending, waiting for the touch events to be processed
5038 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5039 ASSERT_FALSE(keySequenceNum);
5040
5041 std::this_thread::sleep_for(500ms);
5042 // if we wait long enough though, dispatcher will give up, and still send the key
5043 // to the focused window, even though we have not yet finished the motion event
5044 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5045 mWindow->finishEvent(*downSequenceNum);
5046 mWindow->finishEvent(*upSequenceNum);
5047}
5048
5049/**
5050 * If a window is processing a motion event, and then a key event comes in, the key event should
5051 * not go to the focused window until the motion is processed.
5052 * If then a new motion comes in, then the pending key event should be going to the currently
5053 * focused window right away.
5054 */
5055TEST_F(InputDispatcherSingleWindowAnr,
5056 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5057 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5058 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5059
5060 tapOnWindow();
5061 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5062 ASSERT_TRUE(downSequenceNum);
5063 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5064 ASSERT_TRUE(upSequenceNum);
5065 // Don't finish the events yet, and send a key
5066 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005068 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005069 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005070 // At this point, key is still pending, and should not be sent to the application yet.
5071 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5072 ASSERT_FALSE(keySequenceNum);
5073
5074 // Now tap down again. It should cause the pending key to go to the focused window right away.
5075 tapOnWindow();
5076 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5077 // the other events yet. We can finish events in any order.
5078 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5079 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5080 mWindow->consumeMotionDown();
5081 mWindow->consumeMotionUp();
5082 mWindow->assertNoEvents();
5083}
5084
5085class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5086 virtual void SetUp() override {
5087 InputDispatcherTest::SetUp();
5088
Chris Yea209fde2020-07-22 13:54:51 -07005089 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090 mApplication->setDispatchingTimeout(10ms);
5091 mUnfocusedWindow =
5092 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5093 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005095 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096
5097 mFocusedWindow =
5098 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005099 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005101
5102 // Set focused application.
5103 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005104 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005105
5106 // Expect one focus window exist in display.
5107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005108 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005109 mFocusedWindow->consumeFocusEvent(true);
5110 }
5111
5112 virtual void TearDown() override {
5113 InputDispatcherTest::TearDown();
5114
5115 mUnfocusedWindow.clear();
5116 mFocusedWindow.clear();
5117 }
5118
5119protected:
Chris Yea209fde2020-07-22 13:54:51 -07005120 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 sp<FakeWindowHandle> mUnfocusedWindow;
5122 sp<FakeWindowHandle> mFocusedWindow;
5123 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5124 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5125 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5126
5127 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5128
5129 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5130
5131private:
5132 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005134 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5135 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005137 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5138 location));
5139 }
5140};
5141
5142// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5143// should be ANR'd first.
5144TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005145 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005146 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5147 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005148 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005149 mFocusedWindow->consumeMotionDown();
5150 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5151 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5152 // We consumed all events, so no ANR
5153 ASSERT_TRUE(mDispatcher->waitForIdle());
5154 mFakePolicy->assertNotifyAnrWasNotCalled();
5155
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005157 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5158 FOCUSED_WINDOW_LOCATION));
5159 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5160 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005161
5162 const std::chrono::duration timeout =
5163 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005164 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005165 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5166 // sequence to make it consistent
5167 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005168 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005169 mFocusedWindow->consumeMotionDown();
5170 // This cancel is generated because the connection was unresponsive
5171 mFocusedWindow->consumeMotionCancel();
5172 mFocusedWindow->assertNoEvents();
5173 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005174 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005175 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5176 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005177 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005178}
5179
5180// If we have 2 windows with identical timeouts that are both unresponsive,
5181// it doesn't matter which order they should have ANR.
5182// But we should receive ANR for both.
5183TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5184 // Set the timeout for unfocused window to match the focused window
5185 mUnfocusedWindow->setDispatchingTimeout(10ms);
5186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5187
5188 tapOnFocusedWindow();
5189 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005190 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5191 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5192 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005193
5194 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005195 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5196 mFocusedWindow->getToken() == anrConnectionToken2);
5197 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5198 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199
5200 ASSERT_TRUE(mDispatcher->waitForIdle());
5201 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005202
5203 mFocusedWindow->consumeMotionDown();
5204 mFocusedWindow->consumeMotionUp();
5205 mUnfocusedWindow->consumeMotionOutside();
5206
Prabir Pradhanedd96402022-02-15 01:46:16 -08005207 sp<IBinder> responsiveToken1, responsiveToken2;
5208 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5209 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005210
5211 // Both applications should be marked as responsive, in any order
5212 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5213 mFocusedWindow->getToken() == responsiveToken2);
5214 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5215 mUnfocusedWindow->getToken() == responsiveToken2);
5216 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217}
5218
5219// If a window is already not responding, the second tap on the same window should be ignored.
5220// We should also log an error to account for the dropped event (not tested here).
5221// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5222TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5223 tapOnFocusedWindow();
5224 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5225 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5226 // Receive the events, but don't respond
5227 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5228 ASSERT_TRUE(downEventSequenceNum);
5229 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5230 ASSERT_TRUE(upEventSequenceNum);
5231 const std::chrono::duration timeout =
5232 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005233 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234
5235 // Tap once again
5236 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005237 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5239 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005240 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5242 FOCUSED_WINDOW_LOCATION));
5243 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5244 // valid touch target
5245 mUnfocusedWindow->assertNoEvents();
5246
5247 // Consume the first tap
5248 mFocusedWindow->finishEvent(*downEventSequenceNum);
5249 mFocusedWindow->finishEvent(*upEventSequenceNum);
5250 ASSERT_TRUE(mDispatcher->waitForIdle());
5251 // The second tap did not go to the focused window
5252 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005253 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005254 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5255 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 mFakePolicy->assertNotifyAnrWasNotCalled();
5257}
5258
5259// If you tap outside of all windows, there will not be ANR
5260TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005261 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5263 LOCATION_OUTSIDE_ALL_WINDOWS));
5264 ASSERT_TRUE(mDispatcher->waitForIdle());
5265 mFakePolicy->assertNotifyAnrWasNotCalled();
5266}
5267
5268// Since the focused window is paused, tapping on it should not produce any events
5269TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5270 mFocusedWindow->setPaused(true);
5271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5272
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005273 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005274 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5275 FOCUSED_WINDOW_LOCATION));
5276
5277 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5278 ASSERT_TRUE(mDispatcher->waitForIdle());
5279 // Should not ANR because the window is paused, and touches shouldn't go to it
5280 mFakePolicy->assertNotifyAnrWasNotCalled();
5281
5282 mFocusedWindow->assertNoEvents();
5283 mUnfocusedWindow->assertNoEvents();
5284}
5285
5286/**
5287 * If a window is processing a motion event, and then a key event comes in, the key event should
5288 * not to to the focused window until the motion is processed.
5289 * If a different window becomes focused at this time, the key should go to that window instead.
5290 *
5291 * Warning!!!
5292 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5293 * and the injection timeout that we specify when injecting the key.
5294 * We must have the injection timeout (10ms) be smaller than
5295 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5296 *
5297 * If that value changes, this test should also change.
5298 */
5299TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5300 // Set a long ANR timeout to prevent it from triggering
5301 mFocusedWindow->setDispatchingTimeout(2s);
5302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5303
5304 tapOnUnfocusedWindow();
5305 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5306 ASSERT_TRUE(downSequenceNum);
5307 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5308 ASSERT_TRUE(upSequenceNum);
5309 // Don't finish the events yet, and send a key
5310 // Injection will succeed because we will eventually give up and send the key to the focused
5311 // window even if motions are still being processed.
5312
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005313 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005314 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005315 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317 // Key will not be sent to the window, yet, because the window is still processing events
5318 // and the key remains pending, waiting for the touch events to be processed
5319 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5320 ASSERT_FALSE(keySequenceNum);
5321
5322 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005323 mFocusedWindow->setFocusable(false);
5324 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005326 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005327
5328 // Focus events should precede the key events
5329 mUnfocusedWindow->consumeFocusEvent(true);
5330 mFocusedWindow->consumeFocusEvent(false);
5331
5332 // Finish the tap events, which should unblock dispatcher
5333 mUnfocusedWindow->finishEvent(*downSequenceNum);
5334 mUnfocusedWindow->finishEvent(*upSequenceNum);
5335
5336 // Now that all queues are cleared and no backlog in the connections, the key event
5337 // can finally go to the newly focused "mUnfocusedWindow".
5338 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5339 mFocusedWindow->assertNoEvents();
5340 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005341 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005342}
5343
5344// When the touch stream is split across 2 windows, and one of them does not respond,
5345// then ANR should be raised and the touch should be canceled for the unresponsive window.
5346// The other window should not be affected by that.
5347TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5348 // Touch Window 1
5349 NotifyMotionArgs motionArgs =
5350 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5351 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5352 mDispatcher->notifyMotion(&motionArgs);
5353 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5354 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5355
5356 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005357 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5358 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005359 mDispatcher->notifyMotion(&motionArgs);
5360
5361 const std::chrono::duration timeout =
5362 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005363 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005364
5365 mUnfocusedWindow->consumeMotionDown();
5366 mFocusedWindow->consumeMotionDown();
5367 // Focused window may or may not receive ACTION_MOVE
5368 // But it should definitely receive ACTION_CANCEL due to the ANR
5369 InputEvent* event;
5370 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5371 ASSERT_TRUE(moveOrCancelSequenceNum);
5372 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5373 ASSERT_NE(nullptr, event);
5374 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5375 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5376 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5377 mFocusedWindow->consumeMotionCancel();
5378 } else {
5379 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5380 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005381 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005382 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5383 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005384
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005385 mUnfocusedWindow->assertNoEvents();
5386 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005387 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005388}
5389
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005390/**
5391 * If we have no focused window, and a key comes in, we start the ANR timer.
5392 * The focused application should add a focused window before the timer runs out to prevent ANR.
5393 *
5394 * If the user touches another application during this time, the key should be dropped.
5395 * Next, if a new focused window comes in, without toggling the focused application,
5396 * then no ANR should occur.
5397 *
5398 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5399 * but in some cases the policy may not update the focused application.
5400 */
5401TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5402 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5403 std::make_shared<FakeApplicationHandle>();
5404 focusedApplication->setDispatchingTimeout(60ms);
5405 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5406 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5407 mFocusedWindow->setFocusable(false);
5408
5409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5410 mFocusedWindow->consumeFocusEvent(false);
5411
5412 // Send a key. The ANR timer should start because there is no focused window.
5413 // 'focusedApplication' will get blamed if this timer completes.
5414 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005415 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005416 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005417 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5418 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005420
5421 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5422 // then the injected touches won't cause the focused event to get dropped.
5423 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5424 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5425 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5426 // For this test, it means that the key would get delivered to the window once it becomes
5427 // focused.
5428 std::this_thread::sleep_for(10ms);
5429
5430 // Touch unfocused window. This should force the pending key to get dropped.
5431 NotifyMotionArgs motionArgs =
5432 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5433 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5434 mDispatcher->notifyMotion(&motionArgs);
5435
5436 // We do not consume the motion right away, because that would require dispatcher to first
5437 // process (== drop) the key event, and by that time, ANR will be raised.
5438 // Set the focused window first.
5439 mFocusedWindow->setFocusable(true);
5440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5441 setFocusedWindow(mFocusedWindow);
5442 mFocusedWindow->consumeFocusEvent(true);
5443 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5444 // to another application. This could be a bug / behaviour in the policy.
5445
5446 mUnfocusedWindow->consumeMotionDown();
5447
5448 ASSERT_TRUE(mDispatcher->waitForIdle());
5449 // Should not ANR because we actually have a focused window. It was just added too slowly.
5450 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5451}
5452
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005453// These tests ensure we cannot send touch events to a window that's positioned behind a window
5454// that has feature NO_INPUT_CHANNEL.
5455// Layout:
5456// Top (closest to user)
5457// mNoInputWindow (above all windows)
5458// mBottomWindow
5459// Bottom (furthest from user)
5460class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5461 virtual void SetUp() override {
5462 InputDispatcherTest::SetUp();
5463
5464 mApplication = std::make_shared<FakeApplicationHandle>();
5465 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5466 "Window without input channel", ADISPLAY_ID_DEFAULT,
5467 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
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 // It's perfectly valid for this window to not have an associated input channel
5472
5473 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5474 ADISPLAY_ID_DEFAULT);
5475 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5476
5477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5478 }
5479
5480protected:
5481 std::shared_ptr<FakeApplicationHandle> mApplication;
5482 sp<FakeWindowHandle> mNoInputWindow;
5483 sp<FakeWindowHandle> mBottomWindow;
5484};
5485
5486TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5487 PointF touchedPoint = {10, 10};
5488
5489 NotifyMotionArgs motionArgs =
5490 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5491 ADISPLAY_ID_DEFAULT, {touchedPoint});
5492 mDispatcher->notifyMotion(&motionArgs);
5493
5494 mNoInputWindow->assertNoEvents();
5495 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5496 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5497 // and therefore should prevent mBottomWindow from receiving touches
5498 mBottomWindow->assertNoEvents();
5499}
5500
5501/**
5502 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5503 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5504 */
5505TEST_F(InputDispatcherMultiWindowOcclusionTests,
5506 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5507 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5508 "Window with input channel and NO_INPUT_CHANNEL",
5509 ADISPLAY_ID_DEFAULT);
5510
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005511 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005512 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5514
5515 PointF touchedPoint = {10, 10};
5516
5517 NotifyMotionArgs motionArgs =
5518 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5519 ADISPLAY_ID_DEFAULT, {touchedPoint});
5520 mDispatcher->notifyMotion(&motionArgs);
5521
5522 mNoInputWindow->assertNoEvents();
5523 mBottomWindow->assertNoEvents();
5524}
5525
Vishnu Nair958da932020-08-21 17:12:37 -07005526class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5527protected:
5528 std::shared_ptr<FakeApplicationHandle> mApp;
5529 sp<FakeWindowHandle> mWindow;
5530 sp<FakeWindowHandle> mMirror;
5531
5532 virtual void SetUp() override {
5533 InputDispatcherTest::SetUp();
5534 mApp = std::make_shared<FakeApplicationHandle>();
5535 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5536 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5537 mWindow->getToken());
5538 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5539 mWindow->setFocusable(true);
5540 mMirror->setFocusable(true);
5541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5542 }
5543};
5544
5545TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5546 // Request focus on a mirrored window
5547 setFocusedWindow(mMirror);
5548
5549 // window gets focused
5550 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5552 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005553 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5554}
5555
5556// A focused & mirrored window remains focused only if the window and its mirror are both
5557// focusable.
5558TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5559 setFocusedWindow(mMirror);
5560
5561 // window gets focused
5562 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5564 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005565 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5567 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005568 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5569
5570 mMirror->setFocusable(false);
5571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5572
5573 // window loses focus since one of the windows associated with the token in not focusable
5574 mWindow->consumeFocusEvent(false);
5575
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005576 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5577 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005578 mWindow->assertNoEvents();
5579}
5580
5581// A focused & mirrored window remains focused until the window and its mirror both become
5582// invisible.
5583TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5584 setFocusedWindow(mMirror);
5585
5586 // window gets focused
5587 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5589 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005590 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5592 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005593 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5594
5595 mMirror->setVisible(false);
5596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5597
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5599 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005600 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5602 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005603 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5604
5605 mWindow->setVisible(false);
5606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5607
5608 // window loses focus only after all windows associated with the token become invisible.
5609 mWindow->consumeFocusEvent(false);
5610
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005611 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5612 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005613 mWindow->assertNoEvents();
5614}
5615
5616// A focused & mirrored window remains focused until both windows are removed.
5617TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5618 setFocusedWindow(mMirror);
5619
5620 // window gets focused
5621 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5623 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005624 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005627 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5628
5629 // single window is removed but the window token remains focused
5630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5631
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5633 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005634 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5636 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005637 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5638
5639 // Both windows are removed
5640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5641 mWindow->consumeFocusEvent(false);
5642
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005643 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5644 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005645 mWindow->assertNoEvents();
5646}
5647
5648// Focus request can be pending until one window becomes visible.
5649TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5650 // Request focus on an invisible mirror.
5651 mWindow->setVisible(false);
5652 mMirror->setVisible(false);
5653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5654 setFocusedWindow(mMirror);
5655
5656 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005658 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005659 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005660
5661 mMirror->setVisible(true);
5662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5663
5664 // window gets focused
5665 mWindow->consumeFocusEvent(true);
5666 // window gets the pending key event
5667 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5668}
Prabir Pradhan99987712020-11-10 18:43:05 -08005669
5670class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5671protected:
5672 std::shared_ptr<FakeApplicationHandle> mApp;
5673 sp<FakeWindowHandle> mWindow;
5674 sp<FakeWindowHandle> mSecondWindow;
5675
5676 void SetUp() override {
5677 InputDispatcherTest::SetUp();
5678 mApp = std::make_shared<FakeApplicationHandle>();
5679 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5680 mWindow->setFocusable(true);
5681 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5682 mSecondWindow->setFocusable(true);
5683
5684 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5686
5687 setFocusedWindow(mWindow);
5688 mWindow->consumeFocusEvent(true);
5689 }
5690
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005691 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5692 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005693 mDispatcher->notifyPointerCaptureChanged(&args);
5694 }
5695
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005696 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5697 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005698 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005699 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5700 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005701 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005702 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005703 }
5704};
5705
5706TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5707 // Ensure that capture cannot be obtained for unfocused windows.
5708 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5709 mFakePolicy->assertSetPointerCaptureNotCalled();
5710 mSecondWindow->assertNoEvents();
5711
5712 // Ensure that capture can be enabled from the focus window.
5713 requestAndVerifyPointerCapture(mWindow, true);
5714
5715 // Ensure that capture cannot be disabled from a window that does not have capture.
5716 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5717 mFakePolicy->assertSetPointerCaptureNotCalled();
5718
5719 // Ensure that capture can be disabled from the window with capture.
5720 requestAndVerifyPointerCapture(mWindow, false);
5721}
5722
5723TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005724 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005725
5726 setFocusedWindow(mSecondWindow);
5727
5728 // Ensure that the capture disabled event was sent first.
5729 mWindow->consumeCaptureEvent(false);
5730 mWindow->consumeFocusEvent(false);
5731 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005732 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005733
5734 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005735 notifyPointerCaptureChanged({});
5736 notifyPointerCaptureChanged(request);
5737 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005738 mWindow->assertNoEvents();
5739 mSecondWindow->assertNoEvents();
5740 mFakePolicy->assertSetPointerCaptureNotCalled();
5741}
5742
5743TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005744 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005745
5746 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005747 notifyPointerCaptureChanged({});
5748 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005749
5750 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005751 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005752 mWindow->consumeCaptureEvent(false);
5753 mWindow->assertNoEvents();
5754}
5755
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005756TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5757 requestAndVerifyPointerCapture(mWindow, true);
5758
5759 // The first window loses focus.
5760 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005761 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005762 mWindow->consumeCaptureEvent(false);
5763
5764 // Request Pointer Capture from the second window before the notification from InputReader
5765 // arrives.
5766 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005767 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005768
5769 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005770 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005771
5772 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005773 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005774
5775 mSecondWindow->consumeFocusEvent(true);
5776 mSecondWindow->consumeCaptureEvent(true);
5777}
5778
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005779TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5780 // App repeatedly enables and disables capture.
5781 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5782 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5783 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5784 mFakePolicy->assertSetPointerCaptureCalled(false);
5785 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5786 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5787
5788 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5789 // first request is now stale, this should do nothing.
5790 notifyPointerCaptureChanged(firstRequest);
5791 mWindow->assertNoEvents();
5792
5793 // InputReader notifies that the second request was enabled.
5794 notifyPointerCaptureChanged(secondRequest);
5795 mWindow->consumeCaptureEvent(true);
5796}
5797
Prabir Pradhan7092e262022-05-03 16:51:09 +00005798TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5799 requestAndVerifyPointerCapture(mWindow, true);
5800
5801 // App toggles pointer capture off and on.
5802 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5803 mFakePolicy->assertSetPointerCaptureCalled(false);
5804
5805 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5806 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5807
5808 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5809 // preceding "disable" request.
5810 notifyPointerCaptureChanged(enableRequest);
5811
5812 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5813 // any notifications.
5814 mWindow->assertNoEvents();
5815}
5816
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005817class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5818protected:
5819 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005820
5821 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5822 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5823
5824 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5825 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5826
5827 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5828 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5829 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5830 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5831 MAXIMUM_OBSCURING_OPACITY);
5832
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005833 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005834 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005835 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005836
5837 sp<FakeWindowHandle> mTouchWindow;
5838
5839 virtual void SetUp() override {
5840 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005841 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005842 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5843 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5844 }
5845
5846 virtual void TearDown() override {
5847 InputDispatcherTest::TearDown();
5848 mTouchWindow.clear();
5849 }
5850
chaviw3277faf2021-05-19 16:45:23 -05005851 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5852 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005853 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005854 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005855 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005856 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005857 return window;
5858 }
5859
5860 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5861 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5862 sp<FakeWindowHandle> window =
5863 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5864 // Generate an arbitrary PID based on the UID
5865 window->setOwnerInfo(1777 + (uid % 10000), uid);
5866 return window;
5867 }
5868
5869 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5870 NotifyMotionArgs args =
5871 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5872 ADISPLAY_ID_DEFAULT, points);
5873 mDispatcher->notifyMotion(&args);
5874 }
5875};
5876
5877TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005878 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005879 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005881
5882 touch();
5883
5884 mTouchWindow->assertNoEvents();
5885}
5886
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005887TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005888 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5889 const sp<FakeWindowHandle>& w =
5890 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5892
5893 touch();
5894
5895 mTouchWindow->assertNoEvents();
5896}
5897
5898TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005899 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5900 const sp<FakeWindowHandle>& w =
5901 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5903
5904 touch();
5905
5906 w->assertNoEvents();
5907}
5908
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005909TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005910 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005912
5913 touch();
5914
5915 mTouchWindow->consumeAnyMotionDown();
5916}
5917
5918TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005919 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005920 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005921 w->setFrame(Rect(0, 0, 50, 50));
5922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005923
5924 touch({PointF{100, 100}});
5925
5926 mTouchWindow->consumeAnyMotionDown();
5927}
5928
5929TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005930 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005931 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5933
5934 touch();
5935
5936 mTouchWindow->consumeAnyMotionDown();
5937}
5938
5939TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5940 const sp<FakeWindowHandle>& w =
5941 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005943
5944 touch();
5945
5946 mTouchWindow->consumeAnyMotionDown();
5947}
5948
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005949TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5950 const sp<FakeWindowHandle>& w =
5951 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5953
5954 touch();
5955
5956 w->assertNoEvents();
5957}
5958
5959/**
5960 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5961 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5962 * window, the occluding window will still receive ACTION_OUTSIDE event.
5963 */
5964TEST_F(InputDispatcherUntrustedTouchesTest,
5965 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5966 const sp<FakeWindowHandle>& w =
5967 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005968 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5970
5971 touch();
5972
5973 w->consumeMotionOutside();
5974}
5975
5976TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5977 const sp<FakeWindowHandle>& w =
5978 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005979 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5981
5982 touch();
5983
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005984 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005985}
5986
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005987TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005988 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005989 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5990 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5992
5993 touch();
5994
5995 mTouchWindow->consumeAnyMotionDown();
5996}
5997
5998TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5999 const sp<FakeWindowHandle>& w =
6000 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6001 MAXIMUM_OBSCURING_OPACITY);
6002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006003
6004 touch();
6005
6006 mTouchWindow->consumeAnyMotionDown();
6007}
6008
6009TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006010 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006011 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6012 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6014
6015 touch();
6016
6017 mTouchWindow->assertNoEvents();
6018}
6019
6020TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6021 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6022 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006023 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6024 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006025 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006026 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6027 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6029
6030 touch();
6031
6032 mTouchWindow->assertNoEvents();
6033}
6034
6035TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6036 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6037 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006038 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6039 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006040 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006041 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6042 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6044
6045 touch();
6046
6047 mTouchWindow->consumeAnyMotionDown();
6048}
6049
6050TEST_F(InputDispatcherUntrustedTouchesTest,
6051 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6052 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006053 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6054 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006055 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006056 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6057 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006058 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6059
6060 touch();
6061
6062 mTouchWindow->consumeAnyMotionDown();
6063}
6064
6065TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6066 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006067 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6068 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006069 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006070 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6071 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006073
6074 touch();
6075
6076 mTouchWindow->assertNoEvents();
6077}
6078
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006079TEST_F(InputDispatcherUntrustedTouchesTest,
6080 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6081 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006082 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6083 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006084 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006085 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6086 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6088
6089 touch();
6090
6091 mTouchWindow->assertNoEvents();
6092}
6093
6094TEST_F(InputDispatcherUntrustedTouchesTest,
6095 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6096 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006097 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6098 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006099 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006100 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6101 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6103
6104 touch();
6105
6106 mTouchWindow->consumeAnyMotionDown();
6107}
6108
6109TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6110 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006111 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6112 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006113 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6114
6115 touch();
6116
6117 mTouchWindow->consumeAnyMotionDown();
6118}
6119
6120TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6121 const sp<FakeWindowHandle>& w =
6122 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6124
6125 touch();
6126
6127 mTouchWindow->consumeAnyMotionDown();
6128}
6129
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006130TEST_F(InputDispatcherUntrustedTouchesTest,
6131 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6132 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6133 const sp<FakeWindowHandle>& w =
6134 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6136
6137 touch();
6138
6139 mTouchWindow->assertNoEvents();
6140}
6141
6142TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6143 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6144 const sp<FakeWindowHandle>& w =
6145 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6147
6148 touch();
6149
6150 mTouchWindow->consumeAnyMotionDown();
6151}
6152
6153TEST_F(InputDispatcherUntrustedTouchesTest,
6154 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6155 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6156 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006157 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6158 OPACITY_ABOVE_THRESHOLD);
6159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6160
6161 touch();
6162
6163 mTouchWindow->consumeAnyMotionDown();
6164}
6165
6166TEST_F(InputDispatcherUntrustedTouchesTest,
6167 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6168 const sp<FakeWindowHandle>& w1 =
6169 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6170 OPACITY_BELOW_THRESHOLD);
6171 const sp<FakeWindowHandle>& w2 =
6172 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6173 OPACITY_BELOW_THRESHOLD);
6174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6175
6176 touch();
6177
6178 mTouchWindow->assertNoEvents();
6179}
6180
6181/**
6182 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6183 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6184 * (which alone would result in allowing touches) does not affect the blocking behavior.
6185 */
6186TEST_F(InputDispatcherUntrustedTouchesTest,
6187 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6188 const sp<FakeWindowHandle>& wB =
6189 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6190 OPACITY_BELOW_THRESHOLD);
6191 const sp<FakeWindowHandle>& wC =
6192 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6193 OPACITY_BELOW_THRESHOLD);
6194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6195
6196 touch();
6197
6198 mTouchWindow->assertNoEvents();
6199}
6200
6201/**
6202 * This test is testing that a window from a different UID but with same application token doesn't
6203 * block the touch. Apps can share the application token for close UI collaboration for example.
6204 */
6205TEST_F(InputDispatcherUntrustedTouchesTest,
6206 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6207 const sp<FakeWindowHandle>& w =
6208 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6209 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6211
6212 touch();
6213
6214 mTouchWindow->consumeAnyMotionDown();
6215}
6216
arthurhungb89ccb02020-12-30 16:19:01 +08006217class InputDispatcherDragTests : public InputDispatcherTest {
6218protected:
6219 std::shared_ptr<FakeApplicationHandle> mApp;
6220 sp<FakeWindowHandle> mWindow;
6221 sp<FakeWindowHandle> mSecondWindow;
6222 sp<FakeWindowHandle> mDragWindow;
Arthur Hung02701602022-07-15 09:35:36 +00006223 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6224 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006225
6226 void SetUp() override {
6227 InputDispatcherTest::SetUp();
6228 mApp = std::make_shared<FakeApplicationHandle>();
6229 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6230 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006231
6232 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6233 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006234
6235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6236 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6237 }
6238
Arthur Hung02701602022-07-15 09:35:36 +00006239 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6240 switch (fromSource) {
6241 case AINPUT_SOURCE_TOUCHSCREEN:
6242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6243 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6244 ADISPLAY_ID_DEFAULT, {50, 50}))
6245 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6246 break;
6247 case AINPUT_SOURCE_STYLUS:
6248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6249 injectMotionEvent(
6250 mDispatcher,
6251 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6252 AINPUT_SOURCE_STYLUS)
6253 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6254 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6255 .x(50)
6256 .y(50))
6257 .build()));
6258 break;
6259 case AINPUT_SOURCE_MOUSE:
6260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6261 injectMotionEvent(
6262 mDispatcher,
6263 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6264 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6265 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6266 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6267 .x(50)
6268 .y(50))
6269 .build()));
6270 break;
6271 default:
6272 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6273 }
arthurhungb89ccb02020-12-30 16:19:01 +08006274
6275 // Window should receive motion event.
6276 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006277 }
6278
6279 // Start performing drag, we will create a drag window and transfer touch to it.
6280 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6281 // Returns true on success.
Arthur Hung02701602022-07-15 09:35:36 +00006282 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006283 if (sendDown) {
Arthur Hung02701602022-07-15 09:35:36 +00006284 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006285 }
arthurhungb89ccb02020-12-30 16:19:01 +08006286
6287 // The drag window covers the entire display
6288 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6289 mDispatcher->setInputWindows(
6290 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6291
6292 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006293 bool transferred =
6294 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6295 true /* isDragDrop */);
6296 if (transferred) {
6297 mWindow->consumeMotionCancel();
6298 mDragWindow->consumeMotionDown();
6299 }
6300 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006301 }
6302};
6303
6304TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hung02701602022-07-15 09:35:36 +00006305 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006306
6307 // Move on window.
6308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6309 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6310 ADISPLAY_ID_DEFAULT, {50, 50}))
6311 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6312 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6313 mWindow->consumeDragEvent(false, 50, 50);
6314 mSecondWindow->assertNoEvents();
6315
6316 // Move to another window.
6317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6318 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6319 ADISPLAY_ID_DEFAULT, {150, 50}))
6320 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6321 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6322 mWindow->consumeDragEvent(true, 150, 50);
6323 mSecondWindow->consumeDragEvent(false, 50, 50);
6324
6325 // Move back to original window.
6326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6327 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6328 ADISPLAY_ID_DEFAULT, {50, 50}))
6329 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6330 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6331 mWindow->consumeDragEvent(false, 50, 50);
6332 mSecondWindow->consumeDragEvent(true, -50, 50);
6333
6334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6335 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6336 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6337 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6338 mWindow->assertNoEvents();
6339 mSecondWindow->assertNoEvents();
6340}
6341
arthurhungf452d0b2021-01-06 00:19:52 +08006342TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006343 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006344
6345 // Move on window.
6346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6347 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6348 ADISPLAY_ID_DEFAULT, {50, 50}))
6349 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6350 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6351 mWindow->consumeDragEvent(false, 50, 50);
6352 mSecondWindow->assertNoEvents();
6353
6354 // Move to another window.
6355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6356 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6357 ADISPLAY_ID_DEFAULT, {150, 50}))
6358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6359 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6360 mWindow->consumeDragEvent(true, 150, 50);
6361 mSecondWindow->consumeDragEvent(false, 50, 50);
6362
6363 // drop to another window.
6364 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6365 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6366 {150, 50}))
6367 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6368 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6369 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6370 mWindow->assertNoEvents();
6371 mSecondWindow->assertNoEvents();
6372}
6373
arthurhung6d4bed92021-03-17 11:59:33 +08006374TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00006375 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006376
6377 // Move on window and keep button pressed.
6378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6379 injectMotionEvent(mDispatcher,
6380 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6381 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6382 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6383 .x(50)
6384 .y(50))
6385 .build()))
6386 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6387 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6388 mWindow->consumeDragEvent(false, 50, 50);
6389 mSecondWindow->assertNoEvents();
6390
6391 // Move to another window and release button, expect to drop item.
6392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6393 injectMotionEvent(mDispatcher,
6394 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6395 .buttonState(0)
6396 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6397 .x(150)
6398 .y(50))
6399 .build()))
6400 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6401 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6402 mWindow->assertNoEvents();
6403 mSecondWindow->assertNoEvents();
6404 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6405
6406 // nothing to the window.
6407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6408 injectMotionEvent(mDispatcher,
6409 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6410 .buttonState(0)
6411 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6412 .x(150)
6413 .y(50))
6414 .build()))
6415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6416 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6417 mWindow->assertNoEvents();
6418 mSecondWindow->assertNoEvents();
6419}
6420
Arthur Hung54745652022-04-20 07:17:41 +00006421TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung02701602022-07-15 09:35:36 +00006422 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006423
6424 // Set second window invisible.
6425 mSecondWindow->setVisible(false);
6426 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6427
6428 // Move on window.
6429 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6430 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6431 ADISPLAY_ID_DEFAULT, {50, 50}))
6432 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6433 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6434 mWindow->consumeDragEvent(false, 50, 50);
6435 mSecondWindow->assertNoEvents();
6436
6437 // Move to another window.
6438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6439 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6440 ADISPLAY_ID_DEFAULT, {150, 50}))
6441 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6442 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6443 mWindow->consumeDragEvent(true, 150, 50);
6444 mSecondWindow->assertNoEvents();
6445
6446 // drop to another window.
6447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6448 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6449 {150, 50}))
6450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6451 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6452 mFakePolicy->assertDropTargetEquals(nullptr);
6453 mWindow->assertNoEvents();
6454 mSecondWindow->assertNoEvents();
6455}
6456
Arthur Hung54745652022-04-20 07:17:41 +00006457TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hung02701602022-07-15 09:35:36 +00006458 // Ensure window could track pointerIds if it didn't support split touch.
6459 mWindow->setPreventSplitting(true);
6460
Arthur Hung54745652022-04-20 07:17:41 +00006461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6463 {50, 50}))
6464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6465 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6466
6467 const MotionEvent secondFingerDownEvent =
6468 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6469 .displayId(ADISPLAY_ID_DEFAULT)
6470 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6471 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6472 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6473 .build();
6474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6475 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6476 InputEventInjectionSync::WAIT_FOR_RESULT))
6477 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6478 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6479
6480 // Should not perform drag and drop when window has multi fingers.
Arthur Hung02701602022-07-15 09:35:36 +00006481 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006482}
6483
6484TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6485 // First down on second window.
6486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6487 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6488 {150, 50}))
6489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6490
6491 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6492
6493 // Second down on first window.
6494 const MotionEvent secondFingerDownEvent =
6495 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6496 .displayId(ADISPLAY_ID_DEFAULT)
6497 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6498 .pointer(
6499 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6500 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6501 .build();
6502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6503 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6504 InputEventInjectionSync::WAIT_FOR_RESULT))
6505 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6506 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6507
6508 // Perform drag and drop from first window.
Arthur Hung02701602022-07-15 09:35:36 +00006509 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006510
6511 // Move on window.
6512 const MotionEvent secondFingerMoveEvent =
6513 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6514 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6515 .pointer(
6516 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6517 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6518 .build();
6519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6520 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6521 InputEventInjectionSync::WAIT_FOR_RESULT));
6522 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6523 mWindow->consumeDragEvent(false, 50, 50);
6524 mSecondWindow->consumeMotionMove();
6525
6526 // Release the drag pointer should perform drop.
6527 const MotionEvent secondFingerUpEvent =
6528 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6529 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6530 .pointer(
6531 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6532 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6533 .build();
6534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6535 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6536 InputEventInjectionSync::WAIT_FOR_RESULT));
6537 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6538 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6539 mWindow->assertNoEvents();
6540 mSecondWindow->consumeMotionMove();
6541}
6542
Arthur Hung3915c1f2022-05-31 07:17:17 +00006543TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hung02701602022-07-15 09:35:36 +00006544 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006545
6546 // Update window of second display.
6547 sp<FakeWindowHandle> windowInSecondary =
6548 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6549 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6550
6551 // Let second display has a touch state.
6552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6553 injectMotionEvent(mDispatcher,
6554 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6555 AINPUT_SOURCE_TOUCHSCREEN)
6556 .displayId(SECOND_DISPLAY_ID)
6557 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6558 .x(100)
6559 .y(100))
6560 .build()));
6561 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6562 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6563 // Update window again.
6564 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6565
6566 // Move on window.
6567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6568 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6569 ADISPLAY_ID_DEFAULT, {50, 50}))
6570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6571 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6572 mWindow->consumeDragEvent(false, 50, 50);
6573 mSecondWindow->assertNoEvents();
6574
6575 // Move to another window.
6576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6577 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6578 ADISPLAY_ID_DEFAULT, {150, 50}))
6579 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6580 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6581 mWindow->consumeDragEvent(true, 150, 50);
6582 mSecondWindow->consumeDragEvent(false, 50, 50);
6583
6584 // drop to another window.
6585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6586 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6587 {150, 50}))
6588 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6589 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6590 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6591 mWindow->assertNoEvents();
6592 mSecondWindow->assertNoEvents();
6593}
6594
Arthur Hung02701602022-07-15 09:35:36 +00006595TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6596 startDrag(true, AINPUT_SOURCE_MOUSE);
6597 // Move on window.
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionEvent(mDispatcher,
6600 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6601 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6602 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6603 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6604 .x(50)
6605 .y(50))
6606 .build()))
6607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6608 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6609 mWindow->consumeDragEvent(false, 50, 50);
6610 mSecondWindow->assertNoEvents();
6611
6612 // Move to another window.
6613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6614 injectMotionEvent(mDispatcher,
6615 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6616 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6617 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6618 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6619 .x(150)
6620 .y(50))
6621 .build()))
6622 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6623 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6624 mWindow->consumeDragEvent(true, 150, 50);
6625 mSecondWindow->consumeDragEvent(false, 50, 50);
6626
6627 // drop to another window.
6628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6629 injectMotionEvent(mDispatcher,
6630 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6631 .buttonState(0)
6632 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6633 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6634 .x(150)
6635 .y(50))
6636 .build()))
6637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6638 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6639 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6640 mWindow->assertNoEvents();
6641 mSecondWindow->assertNoEvents();
6642}
6643
Vishnu Nair062a8672021-09-03 16:07:44 -07006644class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6645
6646TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6647 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6648 sp<FakeWindowHandle> window =
6649 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006650 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006651 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6652 window->setFocusable(true);
6653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6654 setFocusedWindow(window);
6655 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6656
6657 // With the flag set, window should not get any input
6658 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6659 mDispatcher->notifyKey(&keyArgs);
6660 window->assertNoEvents();
6661
6662 NotifyMotionArgs motionArgs =
6663 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6664 ADISPLAY_ID_DEFAULT);
6665 mDispatcher->notifyMotion(&motionArgs);
6666 window->assertNoEvents();
6667
6668 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006669 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6671
6672 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6673 mDispatcher->notifyKey(&keyArgs);
6674 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6675
6676 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6677 ADISPLAY_ID_DEFAULT);
6678 mDispatcher->notifyMotion(&motionArgs);
6679 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6680 window->assertNoEvents();
6681}
6682
6683TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6684 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6685 std::make_shared<FakeApplicationHandle>();
6686 sp<FakeWindowHandle> obscuringWindow =
6687 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6688 ADISPLAY_ID_DEFAULT);
6689 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6690 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006691 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006692 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6693 sp<FakeWindowHandle> window =
6694 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006695 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006696 window->setOwnerInfo(222, 222);
6697 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6698 window->setFocusable(true);
6699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6700 setFocusedWindow(window);
6701 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6702
6703 // With the flag set, window should not get any input
6704 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6705 mDispatcher->notifyKey(&keyArgs);
6706 window->assertNoEvents();
6707
6708 NotifyMotionArgs motionArgs =
6709 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6710 ADISPLAY_ID_DEFAULT);
6711 mDispatcher->notifyMotion(&motionArgs);
6712 window->assertNoEvents();
6713
6714 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006715 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6717
6718 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6719 mDispatcher->notifyKey(&keyArgs);
6720 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6721
6722 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6723 ADISPLAY_ID_DEFAULT);
6724 mDispatcher->notifyMotion(&motionArgs);
6725 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6726 window->assertNoEvents();
6727}
6728
6729TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6730 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6731 std::make_shared<FakeApplicationHandle>();
6732 sp<FakeWindowHandle> obscuringWindow =
6733 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6734 ADISPLAY_ID_DEFAULT);
6735 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6736 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006737 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006738 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6739 sp<FakeWindowHandle> window =
6740 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006741 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006742 window->setOwnerInfo(222, 222);
6743 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6744 window->setFocusable(true);
6745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6746 setFocusedWindow(window);
6747 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6748
6749 // With the flag set, window should not get any input
6750 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6751 mDispatcher->notifyKey(&keyArgs);
6752 window->assertNoEvents();
6753
6754 NotifyMotionArgs motionArgs =
6755 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6756 ADISPLAY_ID_DEFAULT);
6757 mDispatcher->notifyMotion(&motionArgs);
6758 window->assertNoEvents();
6759
6760 // When the window is no longer obscured because it went on top, it should get input
6761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6762
6763 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6764 mDispatcher->notifyKey(&keyArgs);
6765 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6766
6767 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6768 ADISPLAY_ID_DEFAULT);
6769 mDispatcher->notifyMotion(&motionArgs);
6770 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6771 window->assertNoEvents();
6772}
6773
Antonio Kantekf16f2832021-09-28 04:39:20 +00006774class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6775protected:
6776 std::shared_ptr<FakeApplicationHandle> mApp;
6777 sp<FakeWindowHandle> mWindow;
6778 sp<FakeWindowHandle> mSecondWindow;
6779
6780 void SetUp() override {
6781 InputDispatcherTest::SetUp();
6782
6783 mApp = std::make_shared<FakeApplicationHandle>();
6784 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6785 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006786 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006787 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6788 mSecondWindow->setFocusable(true);
6789
6790 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006792 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006793
6794 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00006795 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6796 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006797 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6798 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6799 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006800 }
6801
Antonio Kantekea47acb2021-12-23 12:41:25 -08006802 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006803 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006804 mWindow->consumeTouchModeEvent(inTouchMode);
6805 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6806 }
6807};
6808
Antonio Kantek26defcf2022-02-08 01:12:27 +00006809TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006810 const WindowInfo& windowInfo = *mWindow->getInfo();
6811 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6812 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006813}
6814
Antonio Kantek26defcf2022-02-08 01:12:27 +00006815TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6816 const WindowInfo& windowInfo = *mWindow->getInfo();
6817 int32_t ownerPid = windowInfo.ownerPid;
6818 int32_t ownerUid = windowInfo.ownerUid;
6819 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6820 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6821 ownerUid, /* hasPermission */ false));
6822 mWindow->assertNoEvents();
6823 mSecondWindow->assertNoEvents();
6824}
6825
6826TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6827 const WindowInfo& windowInfo = *mWindow->getInfo();
6828 int32_t ownerPid = windowInfo.ownerPid;
6829 int32_t ownerUid = windowInfo.ownerUid;
6830 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6831 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6832 /* hasPermission */ true);
6833}
6834
Antonio Kantekf16f2832021-09-28 04:39:20 +00006835TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006836 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006837 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6838 windowInfo.ownerPid, windowInfo.ownerUid,
6839 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006840 mWindow->assertNoEvents();
6841 mSecondWindow->assertNoEvents();
6842}
6843
Antonio Kantek48710e42022-03-24 14:19:30 -07006844TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6845 // Interact with the window first.
6846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6847 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6848 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6849
6850 // Then remove focus.
6851 mWindow->setFocusable(false);
6852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6853
6854 // Assert that caller can switch touch mode by owning one of the last interacted window.
6855 const WindowInfo& windowInfo = *mWindow->getInfo();
6856 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6857 windowInfo.ownerPid, windowInfo.ownerUid,
6858 /* hasPermission= */ false));
6859}
6860
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006861class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6862public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006863 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006864 std::shared_ptr<FakeApplicationHandle> application =
6865 std::make_shared<FakeApplicationHandle>();
6866 std::string name = "Fake Spy ";
6867 name += std::to_string(mSpyCount++);
6868 sp<FakeWindowHandle> spy =
6869 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006870 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006871 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006872 return spy;
6873 }
6874
6875 sp<FakeWindowHandle> createForeground() {
6876 std::shared_ptr<FakeApplicationHandle> application =
6877 std::make_shared<FakeApplicationHandle>();
6878 sp<FakeWindowHandle> window =
6879 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006880 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006881 return window;
6882 }
6883
6884private:
6885 int mSpyCount{0};
6886};
6887
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006888using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006889/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006890 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6891 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006892TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6893 ScopedSilentDeath _silentDeath;
6894
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006895 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006896 spy->setTrustedOverlay(false);
6897 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6898 ".* not a trusted overlay");
6899}
6900
6901/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006902 * Input injection into a display with a spy window but no foreground windows should succeed.
6903 */
6904TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006905 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6907
6908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6909 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6910 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6911 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6912}
6913
6914/**
6915 * Verify the order in which different input windows receive events. The touched foreground window
6916 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6917 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6918 * receive events before ones belows it.
6919 *
6920 * Here, we set up a scenario with four windows in the following Z order from the top:
6921 * spy1, spy2, window, spy3.
6922 * We then inject an event and verify that the foreground "window" receives it first, followed by
6923 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6924 * window.
6925 */
6926TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6927 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006928 auto spy1 = createSpy();
6929 auto spy2 = createSpy();
6930 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006931 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6932 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6933 const size_t numChannels = channels.size();
6934
Michael Wright8e9a8562022-02-09 13:44:29 +00006935 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006936 if (!epollFd.ok()) {
6937 FAIL() << "Failed to create epoll fd";
6938 }
6939
6940 for (size_t i = 0; i < numChannels; i++) {
6941 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6942 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6943 FAIL() << "Failed to add fd to epoll";
6944 }
6945 }
6946
6947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6948 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6950
6951 std::vector<size_t> eventOrder;
6952 std::vector<struct epoll_event> events(numChannels);
6953 for (;;) {
6954 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6955 (100ms).count());
6956 if (nFds < 0) {
6957 FAIL() << "Failed to call epoll_wait";
6958 }
6959 if (nFds == 0) {
6960 break; // epoll_wait timed out
6961 }
6962 for (int i = 0; i < nFds; i++) {
6963 ASSERT_EQ(EPOLLIN, events[i].events);
6964 eventOrder.push_back(events[i].data.u64);
6965 channels[i]->consumeMotionDown();
6966 }
6967 }
6968
6969 // Verify the order in which the events were received.
6970 EXPECT_EQ(3u, eventOrder.size());
6971 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6972 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6973 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6974}
6975
6976/**
6977 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6978 */
6979TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6980 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006981 auto spy = createSpy();
6982 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6984
6985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6986 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6988 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6989 spy->assertNoEvents();
6990}
6991
6992/**
6993 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6994 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6995 * to the window.
6996 */
6997TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6998 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006999 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007000 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7002
7003 // Inject an event outside the spy window's touchable region.
7004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7007 window->consumeMotionDown();
7008 spy->assertNoEvents();
7009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7010 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7012 window->consumeMotionUp();
7013 spy->assertNoEvents();
7014
7015 // Inject an event inside the spy window's touchable region.
7016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7017 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7018 {5, 10}))
7019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7020 window->consumeMotionDown();
7021 spy->consumeMotionDown();
7022}
7023
7024/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007025 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007026 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007027 */
7028TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7029 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007030 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007031 auto spy = createSpy();
7032 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007033 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007034 spy->setFrame(Rect{0, 0, 20, 20});
7035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7036
7037 // Inject an event outside the spy window's frame and touchable region.
7038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007039 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7040 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007041 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7042 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007043 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007044}
7045
7046/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007047 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
7048 * any other windows - including other spy windows - will also be cancelled.
7049 */
7050TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
7051 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007052 auto spy1 = createSpy();
7053 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7055
7056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7059 window->consumeMotionDown();
7060 spy1->consumeMotionDown();
7061 spy2->consumeMotionDown();
7062
7063 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007064 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007065 spy2->assertNoEvents();
7066 spy1->consumeMotionCancel();
7067 window->consumeMotionCancel();
7068
7069 // The rest of the gesture should only be sent to the second spy window.
7070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7071 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7072 ADISPLAY_ID_DEFAULT))
7073 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7074 spy2->consumeMotionMove();
7075 spy1->assertNoEvents();
7076 window->assertNoEvents();
7077}
7078
7079/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007080 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7081 * in the middle of the gesture.
7082 */
7083TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
7084 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007085 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7087
7088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7089 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7090 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7091 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7092 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7093
7094 window->releaseChannel();
7095
7096 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7097
7098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7099 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7101 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7102}
7103
7104/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007105 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7106 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007107 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007108TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007109 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007110 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007111
7112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7113
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007114 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7116 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7117 {100, 200}))
7118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007119 spy->consumeMotionDown();
7120 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007121
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007122 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007123 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007124 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007125
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007126 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007127 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007128 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007129 .displayId(ADISPLAY_ID_DEFAULT)
7130 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7131 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7132 .x(100)
7133 .y(200))
7134 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7135 .build();
7136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7137 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7138 InputEventInjectionSync::WAIT_FOR_RESULT))
7139 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7140
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007141 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7142
7143 // Third finger goes down outside all windows, so injection should fail.
7144 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00007145 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007146 .displayId(ADISPLAY_ID_DEFAULT)
7147 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7148 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7149 .x(100)
7150 .y(200))
7151 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7152 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7153 .build();
7154 ASSERT_EQ(InputEventInjectionResult::FAILED,
7155 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7156 InputEventInjectionSync::WAIT_FOR_RESULT))
7157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7158
7159 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007160 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007161}
7162
7163/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007164 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7165 * pointers that are down within its bounds.
7166 */
7167TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7168 auto windowLeft = createForeground();
7169 windowLeft->setFrame({0, 0, 100, 200});
7170 auto windowRight = createForeground();
7171 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007172 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007173 spy->setFrame({0, 0, 200, 200});
7174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7175
7176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7177 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7178 {50, 50}))
7179 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7180 windowLeft->consumeMotionDown();
7181 spy->consumeMotionDown();
7182
7183 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007184 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007185 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7186 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7187 .pointer(
7188 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7189 .build();
7190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7191 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7192 InputEventInjectionSync::WAIT_FOR_RESULT))
7193 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7194 windowRight->consumeMotionDown();
7195 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7196}
7197
7198/**
7199 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7200 * the spy should receive the second pointer with ACTION_DOWN.
7201 */
7202TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7203 auto window = createForeground();
7204 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007205 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007206 spyRight->setFrame({100, 0, 200, 200});
7207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7208
7209 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7210 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7211 {50, 50}))
7212 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7213 window->consumeMotionDown();
7214 spyRight->assertNoEvents();
7215
7216 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007217 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007218 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7219 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7220 .pointer(
7221 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7222 .build();
7223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7224 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7225 InputEventInjectionSync::WAIT_FOR_RESULT))
7226 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7227 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7228 spyRight->consumeMotionDown();
7229}
7230
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007231/**
7232 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7233 * windows should be allowed to control split touch.
7234 */
7235TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007236 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007237 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007238 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007239 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007240
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007241 auto window = createForeground();
7242 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007243
7244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7245
7246 // First finger down, no window touched.
7247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7248 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7249 {100, 200}))
7250 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7251 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7252 window->assertNoEvents();
7253
7254 // Second finger down on window, the window should receive touch down.
7255 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007256 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007257 .displayId(ADISPLAY_ID_DEFAULT)
7258 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7259 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7260 .x(100)
7261 .y(200))
7262 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7263 .build();
7264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7265 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7266 InputEventInjectionSync::WAIT_FOR_RESULT))
7267 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7268
7269 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7270 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7271}
7272
7273/**
7274 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7275 * do not receive key events.
7276 */
7277TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007278 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007279 spy->setFocusable(false);
7280
7281 auto window = createForeground();
7282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7283 setFocusedWindow(window);
7284 window->consumeFocusEvent(true);
7285
7286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7287 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7288 window->consumeKeyDown(ADISPLAY_ID_NONE);
7289
7290 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7291 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7292 window->consumeKeyUp(ADISPLAY_ID_NONE);
7293
7294 spy->assertNoEvents();
7295}
7296
Prabir Pradhand65552b2021-10-07 11:23:50 -07007297class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7298public:
7299 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7300 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7301 std::make_shared<FakeApplicationHandle>();
7302 sp<FakeWindowHandle> overlay =
7303 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7304 ADISPLAY_ID_DEFAULT);
7305 overlay->setFocusable(false);
7306 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007307 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007308 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007309 overlay->setTrustedOverlay(true);
7310
7311 std::shared_ptr<FakeApplicationHandle> application =
7312 std::make_shared<FakeApplicationHandle>();
7313 sp<FakeWindowHandle> window =
7314 new FakeWindowHandle(application, mDispatcher, "Application window",
7315 ADISPLAY_ID_DEFAULT);
7316 window->setFocusable(true);
7317 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007318
7319 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7321 setFocusedWindow(window);
7322 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7323 return {std::move(overlay), std::move(window)};
7324 }
7325
7326 void sendFingerEvent(int32_t action) {
7327 NotifyMotionArgs motionArgs =
7328 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7329 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7330 mDispatcher->notifyMotion(&motionArgs);
7331 }
7332
7333 void sendStylusEvent(int32_t action) {
7334 NotifyMotionArgs motionArgs =
7335 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7336 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7337 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7338 mDispatcher->notifyMotion(&motionArgs);
7339 }
7340};
7341
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007342using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7343
7344TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7345 ScopedSilentDeath _silentDeath;
7346
Prabir Pradhand65552b2021-10-07 11:23:50 -07007347 auto [overlay, window] = setupStylusOverlayScenario();
7348 overlay->setTrustedOverlay(false);
7349 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7350 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7351 ".* not a trusted overlay");
7352}
7353
7354TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7355 auto [overlay, window] = setupStylusOverlayScenario();
7356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7357
7358 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7359 overlay->consumeMotionDown();
7360 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7361 overlay->consumeMotionUp();
7362
7363 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7364 window->consumeMotionDown();
7365 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7366 window->consumeMotionUp();
7367
7368 overlay->assertNoEvents();
7369 window->assertNoEvents();
7370}
7371
7372TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7373 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007374 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7376
7377 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7378 overlay->consumeMotionDown();
7379 window->consumeMotionDown();
7380 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7381 overlay->consumeMotionUp();
7382 window->consumeMotionUp();
7383
7384 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7385 window->consumeMotionDown();
7386 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7387 window->consumeMotionUp();
7388
7389 overlay->assertNoEvents();
7390 window->assertNoEvents();
7391}
7392
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007393/**
7394 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7395 * The scenario is as follows:
7396 * - The stylus interceptor overlay is configured as a spy window.
7397 * - The stylus interceptor spy receives the start of a new stylus gesture.
7398 * - It pilfers pointers and then configures itself to no longer be a spy.
7399 * - The stylus interceptor continues to receive the rest of the gesture.
7400 */
7401TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7402 auto [overlay, window] = setupStylusOverlayScenario();
7403 overlay->setSpy(true);
7404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7405
7406 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7407 overlay->consumeMotionDown();
7408 window->consumeMotionDown();
7409
7410 // The interceptor pilfers the pointers.
7411 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7412 window->consumeMotionCancel();
7413
7414 // The interceptor configures itself so that it is no longer a spy.
7415 overlay->setSpy(false);
7416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7417
7418 // It continues to receive the rest of the stylus gesture.
7419 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7420 overlay->consumeMotionMove();
7421 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7422 overlay->consumeMotionUp();
7423
7424 window->assertNoEvents();
7425}
7426
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007427struct User {
7428 int32_t mPid;
7429 int32_t mUid;
7430 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7431 std::unique_ptr<InputDispatcher>& mDispatcher;
7432
7433 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7434 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7435
7436 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7437 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7438 ADISPLAY_ID_DEFAULT, {100, 200},
7439 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7440 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7441 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7442 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7443 }
7444
7445 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7446 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7447 InputEventInjectionSync::WAIT_FOR_RESULT,
7448 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7449 mPolicyFlags);
7450 }
7451
7452 sp<FakeWindowHandle> createWindow() const {
7453 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7454 std::make_shared<FakeApplicationHandle>();
7455 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7456 "Owned Window", ADISPLAY_ID_DEFAULT);
7457 window->setOwnerInfo(mPid, mUid);
7458 return window;
7459 }
7460};
7461
7462using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7463
7464TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7465 auto owner = User(mDispatcher, 10, 11);
7466 auto window = owner.createWindow();
7467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7468
7469 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7470 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7471 window->consumeMotionDown();
7472
7473 setFocusedWindow(window);
7474 window->consumeFocusEvent(true);
7475
7476 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7477 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7478 window->consumeKeyDown(ADISPLAY_ID_NONE);
7479}
7480
7481TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7482 auto owner = User(mDispatcher, 10, 11);
7483 auto window = owner.createWindow();
7484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7485
7486 auto rando = User(mDispatcher, 20, 21);
7487 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7488 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7489
7490 setFocusedWindow(window);
7491 window->consumeFocusEvent(true);
7492
7493 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7494 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7495 window->assertNoEvents();
7496}
7497
7498TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7499 auto owner = User(mDispatcher, 10, 11);
7500 auto window = owner.createWindow();
7501 auto spy = owner.createWindow();
7502 spy->setSpy(true);
7503 spy->setTrustedOverlay(true);
7504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7505
7506 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7507 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7508 spy->consumeMotionDown();
7509 window->consumeMotionDown();
7510}
7511
7512TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7513 auto owner = User(mDispatcher, 10, 11);
7514 auto window = owner.createWindow();
7515
7516 auto rando = User(mDispatcher, 20, 21);
7517 auto randosSpy = rando.createWindow();
7518 randosSpy->setSpy(true);
7519 randosSpy->setTrustedOverlay(true);
7520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7521
7522 // The event is targeted at owner's window, so injection should succeed, but the spy should
7523 // not receive the event.
7524 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7525 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7526 randosSpy->assertNoEvents();
7527 window->consumeMotionDown();
7528}
7529
7530TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7531 auto owner = User(mDispatcher, 10, 11);
7532 auto window = owner.createWindow();
7533
7534 auto rando = User(mDispatcher, 20, 21);
7535 auto randosSpy = rando.createWindow();
7536 randosSpy->setSpy(true);
7537 randosSpy->setTrustedOverlay(true);
7538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7539
7540 // A user that has injection permission can inject into any window.
7541 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7542 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7543 ADISPLAY_ID_DEFAULT));
7544 randosSpy->consumeMotionDown();
7545 window->consumeMotionDown();
7546
7547 setFocusedWindow(randosSpy);
7548 randosSpy->consumeFocusEvent(true);
7549
7550 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7551 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7552 window->assertNoEvents();
7553}
7554
7555TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7556 auto owner = User(mDispatcher, 10, 11);
7557 auto window = owner.createWindow();
7558
7559 auto rando = User(mDispatcher, 20, 21);
7560 auto randosWindow = rando.createWindow();
7561 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7562 randosWindow->setWatchOutsideTouch(true);
7563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7564
7565 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7566 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7567 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7568 window->consumeMotionDown();
7569 randosWindow->consumeMotionOutside();
7570}
7571
Garfield Tane84e6f92019-08-29 17:28:41 -07007572} // namespace android::inputdispatcher