blob: b3afd5643bcd1dad491bc356e818ac47a762efad [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -070019#include <android-base/properties.h>
Prabir Pradhana3ab87a2022-01-27 10:00:21 -080020#include <android-base/silent_death_test.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080021#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070022#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070023#include <binder/Binder.h>
Michael Wright8e9a8562022-02-09 13:44:29 +000024#include <fcntl.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080028#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100029
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070031#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080032#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080033#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080034
Garfield Tan1c7bc862020-01-28 13:24:04 -080035using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050036using android::gui::FocusRequest;
37using android::gui::TouchOcclusionMode;
38using android::gui::WindowInfo;
39using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080040using android::os::InputEventInjectionResult;
41using android::os::InputEventInjectionSync;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
Dominik Laskowski2f01d772022-03-23 16:01:29 -070045using namespace ftl::flag_operators;
46
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary time value.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000048static constexpr nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
50// An arbitrary device id.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000051static constexpr int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Jeff Brownf086ddb2014-02-11 14:28:48 -080053// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000054static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
55static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080056
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080057static constexpr int32_t POINTER_1_DOWN =
58 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000059static constexpr int32_t POINTER_2_DOWN =
60 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080061static constexpr int32_t POINTER_1_UP =
62 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
63
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +000064// The default pid and uid for windows created by the test.
65static constexpr int32_t WINDOW_PID = 999;
66static constexpr int32_t WINDOW_UID = 1001;
67
68// The default policy flags to use for event injection by tests.
69static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000071// An arbitrary pid of the gesture monitor window
72static constexpr int32_t MONITOR_PID = 2001;
73
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080074static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
75
chaviwd1c23182019-12-20 18:44:56 -080076struct PointF {
77 float x;
78 float y;
79};
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
Gang Wang342c9272020-01-13 13:15:04 -050081/**
82 * Return a DOWN key event with KEYCODE_A.
83 */
84static KeyEvent getTestKeyEvent() {
85 KeyEvent event;
86
Garfield Tanfbe732e2020-01-24 11:26:14 -080087 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
88 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
89 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050090 return event;
91}
92
Siarhei Vishniakouca205502021-07-16 21:31:58 +000093static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
94 ASSERT_EQ(expectedAction, receivedAction)
95 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
96 << MotionEvent::actionToString(receivedAction);
97}
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099// --- FakeInputDispatcherPolicy ---
100
101class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
102 InputDispatcherConfiguration mConfig;
103
Prabir Pradhanedd96402022-02-15 01:46:16 -0800104 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000107 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108
109public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000110 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800111
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800112 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700113 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
114 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
115 EXPECT_EQ(event.getDisplayId(), args.displayId);
116
117 const auto& keyEvent = static_cast<const KeyEvent&>(event);
118 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
119 EXPECT_EQ(keyEvent.getAction(), args.action);
120 });
Jackal Guof9696682018-10-05 12:23:23 +0800121 }
122
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700123 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
124 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
125 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
126 EXPECT_EQ(event.getDisplayId(), args.displayId);
127
128 const auto& motionEvent = static_cast<const MotionEvent&>(event);
129 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
130 EXPECT_EQ(motionEvent.getAction(), args.action);
131 EXPECT_EQ(motionEvent.getX(0), point.x);
132 EXPECT_EQ(motionEvent.getY(0), point.y);
133 EXPECT_EQ(motionEvent.getRawX(0), point.x);
134 EXPECT_EQ(motionEvent.getRawY(0), point.y);
135 });
Jackal Guof9696682018-10-05 12:23:23 +0800136 }
137
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700138 void assertFilterInputEventWasNotCalled() {
139 std::scoped_lock lock(mLock);
140 ASSERT_EQ(nullptr, mFilteredEvent);
141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800143 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700144 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800145 ASSERT_TRUE(mConfigurationChangedTime)
146 << "Timed out waiting for configuration changed call";
147 ASSERT_EQ(*mConfigurationChangedTime, when);
148 mConfigurationChangedTime = std::nullopt;
149 }
150
151 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700152 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800153 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800154 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800155 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
156 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
157 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
158 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
159 mLastNotifySwitch = std::nullopt;
160 }
161
chaviwfd6d3512019-03-25 13:23:49 -0700162 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700163 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800164 ASSERT_EQ(touchedToken, mOnPointerDownToken);
165 mOnPointerDownToken.clear();
166 }
167
168 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700169 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800170 ASSERT_TRUE(mOnPointerDownToken == nullptr)
171 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700172 }
173
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700174 // This function must be called soon after the expected ANR timer starts,
175 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700177 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800179 std::unique_lock lock(mLock);
180 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500181 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800182 ASSERT_NO_FATAL_FAILURE(
183 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500184 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700185 }
186
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000187 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800188 const sp<WindowInfoHandle>& window) {
189 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
190 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
191 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500192 }
193
Prabir Pradhanedd96402022-02-15 01:46:16 -0800194 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
195 const sp<IBinder>& expectedToken,
196 int32_t expectedPid) {
197 std::unique_lock lock(mLock);
198 android::base::ScopedLockAssertion assumeLocked(mLock);
199 AnrResult result;
200 ASSERT_NO_FATAL_FAILURE(result =
201 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
202 const auto& [token, pid] = result;
203 ASSERT_EQ(expectedToken, token);
204 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500205 }
206
Prabir Pradhanedd96402022-02-15 01:46:16 -0800207 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500209 std::unique_lock lock(mLock);
210 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800211 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
212 const auto& [token, _] = result;
213 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000214 }
215
Prabir Pradhanedd96402022-02-15 01:46:16 -0800216 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
217 int32_t expectedPid) {
218 std::unique_lock lock(mLock);
219 android::base::ScopedLockAssertion assumeLocked(mLock);
220 AnrResult result;
221 ASSERT_NO_FATAL_FAILURE(
222 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
223 const auto& [token, pid] = result;
224 ASSERT_EQ(expectedToken, token);
225 ASSERT_EQ(expectedPid, pid);
226 }
227
228 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000229 sp<IBinder> getResponsiveWindowToken() {
230 std::unique_lock lock(mLock);
231 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800232 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
233 const auto& [token, _] = result;
234 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700235 }
236
237 void assertNotifyAnrWasNotCalled() {
238 std::scoped_lock lock(mLock);
239 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800240 ASSERT_TRUE(mAnrWindows.empty());
241 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500242 << "ANR was not called, but please also consume the 'connection is responsive' "
243 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700244 }
245
Garfield Tan1c7bc862020-01-28 13:24:04 -0800246 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
247 mConfig.keyRepeatTimeout = timeout;
248 mConfig.keyRepeatDelay = delay;
249 }
250
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000251 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800252 std::unique_lock lock(mLock);
253 base::ScopedLockAssertion assumeLocked(mLock);
254
255 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
256 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000257 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800258 enabled;
259 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000260 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
261 << ") to be called.";
262 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800263 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000264 auto request = *mPointerCaptureRequest;
265 mPointerCaptureRequest.reset();
266 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800267 }
268
269 void assertSetPointerCaptureNotCalled() {
270 std::unique_lock lock(mLock);
271 base::ScopedLockAssertion assumeLocked(mLock);
272
273 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000274 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800275 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000276 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800277 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800279 }
280
arthurhungf452d0b2021-01-06 00:19:52 +0800281 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
282 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800283 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800284 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800285 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800286 }
287
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800288 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
289 std::unique_lock lock(mLock);
290 base::ScopedLockAssertion assumeLocked(mLock);
291 std::optional<sp<IBinder>> receivedToken =
292 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
293 mNotifyInputChannelBroken);
294 ASSERT_TRUE(receivedToken.has_value());
295 ASSERT_EQ(token, *receivedToken);
296 }
297
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800298 /**
299 * Set policy timeout. A value of zero means next key will not be intercepted.
300 */
301 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
302 mInterceptKeyTimeout = timeout;
303 }
304
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700306 std::mutex mLock;
307 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
308 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
309 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
310 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800311
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000313
314 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800315
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700316 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700317 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800318 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
319 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700320 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800321 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
322 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700323
arthurhungf452d0b2021-01-06 00:19:52 +0800324 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800325 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800326
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800327 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
328
Prabir Pradhanedd96402022-02-15 01:46:16 -0800329 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
330 // for a specific container to become non-empty. When the container is non-empty, return the
331 // first entry from the container and erase it.
332 template <class T>
333 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
334 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
335 // If there is an ANR, Dispatcher won't be idle because there are still events
336 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
337 // before checking if ANR was called.
338 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
339 // to provide it some time to act. 100ms seems reasonable.
340 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
341 const std::chrono::time_point start = std::chrono::steady_clock::now();
342 std::optional<T> token =
343 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
344 if (!token.has_value()) {
345 ADD_FAILURE() << "Did not receive the ANR callback";
346 return {};
347 }
348
349 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
350 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
351 // the dispatcher started counting before this function was called
352 if (std::chrono::abs(timeout - waited) > 100ms) {
353 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
354 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
355 << "ms, but waited "
356 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
357 << "ms instead";
358 }
359 return *token;
360 }
361
362 template <class T>
363 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
364 std::queue<T>& storage,
365 std::unique_lock<std::mutex>& lock,
366 std::condition_variable& condition)
367 REQUIRES(mLock) {
368 condition.wait_for(lock, timeout,
369 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
370 if (storage.empty()) {
371 ADD_FAILURE() << "Did not receive the expected callback";
372 return std::nullopt;
373 }
374 T item = storage.front();
375 storage.pop();
376 return std::make_optional(item);
377 }
378
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600379 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700380 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800381 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
Prabir Pradhanedd96402022-02-15 01:46:16 -0800384 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
385 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700386 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800387 ASSERT_TRUE(pid.has_value());
388 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700389 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500390 }
391
Prabir Pradhanedd96402022-02-15 01:46:16 -0800392 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
393 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500394 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800395 ASSERT_TRUE(pid.has_value());
396 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500397 mNotifyAnr.notify_all();
398 }
399
400 void notifyNoFocusedWindowAnr(
401 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
402 std::scoped_lock lock(mLock);
403 mAnrApplications.push(applicationHandle);
404 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 }
406
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800407 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
408 std::scoped_lock lock(mLock);
409 mBrokenInputChannels.push(connectionToken);
410 mNotifyInputChannelBroken.notify_all();
411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600413 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700416 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
417 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
418 const std::vector<float>& values) override {}
419
420 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
421 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000422
Chris Yefb552902021-02-03 17:18:37 -0800423 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
424
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600425 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 *outConfig = mConfig;
427 }
428
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600429 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700430 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800431 switch (inputEvent->getType()) {
432 case AINPUT_EVENT_TYPE_KEY: {
433 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800434 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800435 break;
436 }
437
438 case AINPUT_EVENT_TYPE_MOTION: {
439 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800440 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800441 break;
442 }
443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 return true;
445 }
446
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800447 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
448 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
449 // Clear intercept state when we handled the event.
450 mInterceptKeyTimeout = 0ms;
451 }
452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600454 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600456 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800457 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
458 // Clear intercept state so we could dispatch the event in next wake.
459 mInterceptKeyTimeout = 0ms;
460 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 }
462
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600463 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 return false;
465 }
466
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600467 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
468 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700469 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800470 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
471 * essentially a passthrough for notifySwitch.
472 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800473 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 }
475
Sean Stoutb4e0a592021-02-23 07:34:53 -0800476 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600478 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700479 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700480 mOnPointerDownToken = newToken;
481 }
482
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000483 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800484 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000485 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800486 mPointerCaptureChangedCondition.notify_all();
487 }
488
arthurhungf452d0b2021-01-06 00:19:52 +0800489 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
490 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800491 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800492 mDropTargetWindowToken = token;
493 }
494
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700495 void assertFilterInputEventWasCalledInternal(
496 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700497 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800498 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700499 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800500 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502};
503
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504// --- InputDispatcherTest ---
505
506class InputDispatcherTest : public testing::Test {
507protected:
508 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700509 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000511 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800513 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800514 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000515 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700516 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 }
518
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000519 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700520 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700522 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700524
525 /**
526 * Used for debugging when writing the test
527 */
528 void dumpDispatcherState() {
529 std::string dump;
530 mDispatcher->dump(dump);
531 std::stringstream ss(dump);
532 std::string to;
533
534 while (std::getline(ss, to, '\n')) {
535 ALOGE("%s", to.c_str());
536 }
537 }
Vishnu Nair958da932020-08-21 17:12:37 -0700538
chaviw3277faf2021-05-19 16:45:23 -0500539 void setFocusedWindow(const sp<WindowInfoHandle>& window,
540 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700541 FocusRequest request;
542 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000543 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700544 if (focusedWindow) {
545 request.focusedToken = focusedWindow->getToken();
546 }
547 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
548 request.displayId = window->getInfo()->displayId;
549 mDispatcher->setFocusedWindow(request);
550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551};
552
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
554 KeyEvent event;
555
556 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800557 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
558 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600559 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
560 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000562 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
563 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 << "Should reject key events with undefined action.";
565
566 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
568 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600569 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800570 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000571 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
572 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 << "Should reject key events with ACTION_MULTIPLE.";
574}
575
576TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
577 MotionEvent event;
578 PointerProperties pointerProperties[MAX_POINTERS + 1];
579 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800580 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 pointerProperties[i].clear();
582 pointerProperties[i].id = i;
583 pointerCoords[i].clear();
584 }
585
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800586 // Some constants commonly used below
587 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
588 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
589 constexpr int32_t metaState = AMETA_NONE;
590 constexpr MotionClassification classification = MotionClassification::NONE;
591
chaviw9eaa22c2020-07-01 16:21:27 -0700592 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800594 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700595 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
596 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700597 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
598 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800600 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000601 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
602 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 << "Should reject motion events with undefined action.";
604
605 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800606 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800607 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
608 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
609 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
610 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500611 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000613 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
614 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 << "Should reject motion events with pointer down index too large.";
616
Garfield Tanfbe732e2020-01-24 11:26:14 -0800617 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700618 AMOTION_EVENT_ACTION_POINTER_DOWN |
619 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700620 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
621 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700622 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500623 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000625 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
626 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 << "Should reject motion events with pointer down index too small.";
628
629 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800630 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800631 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
632 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
633 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
634 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500635 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000637 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
638 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 << "Should reject motion events with pointer up index too large.";
640
Garfield Tanfbe732e2020-01-24 11:26:14 -0800641 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700642 AMOTION_EVENT_ACTION_POINTER_UP |
643 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700644 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
645 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700646 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500647 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800648 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000649 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
650 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 << "Should reject motion events with pointer up index too small.";
652
653 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800654 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
655 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700656 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700657 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
658 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700659 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000661 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
662 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 << "Should reject motion events with 0 pointers.";
664
Garfield Tanfbe732e2020-01-24 11:26:14 -0800665 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
666 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700667 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700668 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
669 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700670 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000672 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
673 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 << "Should reject motion events with more than MAX_POINTERS pointers.";
675
676 // Rejects motion events with invalid pointer ids.
677 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800678 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
679 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700680 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700681 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
682 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700683 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800684 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000685 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
686 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 << "Should reject motion events with pointer ids less than 0.";
688
689 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800690 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
691 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700692 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700693 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
694 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700695 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800696 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000697 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
698 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
700
701 // Rejects motion events with duplicate pointer ids.
702 pointerProperties[0].id = 1;
703 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800704 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
705 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700706 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700707 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
708 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700709 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800710 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000711 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
712 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 << "Should reject motion events with duplicate pointer ids.";
714}
715
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800716/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
717
718TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
719 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800720 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800721 mDispatcher->notifyConfigurationChanged(&args);
722 ASSERT_TRUE(mDispatcher->waitForIdle());
723
724 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
725}
726
727TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800728 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
729 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800730 mDispatcher->notifySwitch(&args);
731
732 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
733 args.policyFlags |= POLICY_FLAG_TRUSTED;
734 mFakePolicy->assertNotifySwitchWasCalled(args);
735}
736
Arthur Hungb92218b2018-08-14 12:00:21 +0800737// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700738static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700739// Default input dispatching timeout if there is no focused application or paused window
740// from which to determine an appropriate dispatching timeout.
741static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
742 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
743 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800744
745class FakeApplicationHandle : public InputApplicationHandle {
746public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700747 FakeApplicationHandle() {
748 mInfo.name = "Fake Application";
749 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500750 mInfo.dispatchingTimeoutMillis =
751 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800753 virtual ~FakeApplicationHandle() {}
754
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000755 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700756
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500757 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
758 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700759 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800760};
761
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800762class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800763public:
Garfield Tan15601662020-09-22 15:32:38 -0700764 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800765 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700766 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800767 }
768
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800769 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700770 InputEvent* event;
771 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
772 if (!consumeSeq) {
773 return nullptr;
774 }
775 finishEvent(*consumeSeq);
776 return event;
777 }
778
779 /**
780 * Receive an event without acknowledging it.
781 * Return the sequence number that could later be used to send finished signal.
782 */
783 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800784 uint32_t consumeSeq;
785 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800786
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800787 std::chrono::time_point start = std::chrono::steady_clock::now();
788 status_t status = WOULD_BLOCK;
789 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800790 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800791 &event);
792 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
793 if (elapsed > 100ms) {
794 break;
795 }
796 }
797
798 if (status == WOULD_BLOCK) {
799 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700800 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800801 }
802
803 if (status != OK) {
804 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700805 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800806 }
807 if (event == nullptr) {
808 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700809 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800810 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700811 if (outEvent != nullptr) {
812 *outEvent = event;
813 }
814 return consumeSeq;
815 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700817 /**
818 * To be used together with "receiveEvent" to complete the consumption of an event.
819 */
820 void finishEvent(uint32_t consumeSeq) {
821 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
822 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800823 }
824
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000825 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
826 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
827 ASSERT_EQ(OK, status);
828 }
829
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000830 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
831 std::optional<int32_t> expectedDisplayId,
832 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800833 InputEvent* event = consume();
834
835 ASSERT_NE(nullptr, event) << mName.c_str()
836 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800837 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800839 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800840
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000841 if (expectedDisplayId.has_value()) {
842 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
843 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800844
Tiger Huang8664f8c2018-10-11 19:14:35 +0800845 switch (expectedEventType) {
846 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800847 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
848 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000849 if (expectedFlags.has_value()) {
850 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
851 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800852 break;
853 }
854 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800855 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000856 assertMotionAction(expectedAction, motionEvent.getAction());
857
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000858 if (expectedFlags.has_value()) {
859 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
860 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800861 break;
862 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100863 case AINPUT_EVENT_TYPE_FOCUS: {
864 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
865 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800866 case AINPUT_EVENT_TYPE_CAPTURE: {
867 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
868 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000869 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
870 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
871 }
arthurhungb89ccb02020-12-30 16:19:01 +0800872 case AINPUT_EVENT_TYPE_DRAG: {
873 FAIL() << "Use 'consumeDragEvent' for DRAG events";
874 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800875 default: {
876 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
877 }
878 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800879 }
880
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100881 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
882 InputEvent* event = consume();
883 ASSERT_NE(nullptr, event) << mName.c_str()
884 << ": consumer should have returned non-NULL event.";
885 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
886 << "Got " << inputEventTypeToString(event->getType())
887 << " event instead of FOCUS event";
888
889 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
890 << mName.c_str() << ": event displayId should always be NONE.";
891
892 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
893 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100894 }
895
Prabir Pradhan99987712020-11-10 18:43:05 -0800896 void consumeCaptureEvent(bool hasCapture) {
897 const InputEvent* event = consume();
898 ASSERT_NE(nullptr, event) << mName.c_str()
899 << ": consumer should have returned non-NULL event.";
900 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
901 << "Got " << inputEventTypeToString(event->getType())
902 << " event instead of CAPTURE event";
903
904 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
905 << mName.c_str() << ": event displayId should always be NONE.";
906
907 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
908 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
909 }
910
arthurhungb89ccb02020-12-30 16:19:01 +0800911 void consumeDragEvent(bool isExiting, float x, float y) {
912 const InputEvent* event = consume();
913 ASSERT_NE(nullptr, event) << mName.c_str()
914 << ": consumer should have returned non-NULL event.";
915 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
916 << "Got " << inputEventTypeToString(event->getType())
917 << " event instead of DRAG event";
918
919 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
920 << mName.c_str() << ": event displayId should always be NONE.";
921
922 const auto& dragEvent = static_cast<const DragEvent&>(*event);
923 EXPECT_EQ(isExiting, dragEvent.isExiting());
924 EXPECT_EQ(x, dragEvent.getX());
925 EXPECT_EQ(y, dragEvent.getY());
926 }
927
Antonio Kantekf16f2832021-09-28 04:39:20 +0000928 void consumeTouchModeEvent(bool inTouchMode) {
929 const InputEvent* event = consume();
930 ASSERT_NE(nullptr, event) << mName.c_str()
931 << ": consumer should have returned non-NULL event.";
932 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
933 << "Got " << inputEventTypeToString(event->getType())
934 << " event instead of TOUCH_MODE event";
935
936 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
937 << mName.c_str() << ": event displayId should always be NONE.";
938 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
939 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
940 }
941
chaviwd1c23182019-12-20 18:44:56 -0800942 void assertNoEvents() {
943 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 if (event == nullptr) {
945 return;
946 }
947 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
948 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
949 ADD_FAILURE() << "Received key event "
950 << KeyEvent::actionToString(keyEvent.getAction());
951 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
952 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
953 ADD_FAILURE() << "Received motion event "
954 << MotionEvent::actionToString(motionEvent.getAction());
955 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
956 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
957 ADD_FAILURE() << "Received focus event, hasFocus = "
958 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800959 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
960 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
961 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
962 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000963 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
964 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
965 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
966 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967 }
968 FAIL() << mName.c_str()
969 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800970 }
971
972 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
973
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800974 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
975
chaviwd1c23182019-12-20 18:44:56 -0800976protected:
977 std::unique_ptr<InputConsumer> mConsumer;
978 PreallocatedInputEventFactory mEventFactory;
979
980 std::string mName;
981};
982
chaviw3277faf2021-05-19 16:45:23 -0500983class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800984public:
985 static const int32_t WIDTH = 600;
986 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800987
Chris Yea209fde2020-07-22 13:54:51 -0700988 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700989 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500990 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800991 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500992 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700993 base::Result<std::unique_ptr<InputChannel>> channel =
994 dispatcher->createInputChannel(name);
995 token = (*channel)->getConnectionToken();
996 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800997 }
998
999 inputApplicationHandle->updateInfo();
1000 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1001
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001002 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001003 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001004 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001005 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001006 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001007 mInfo.frameLeft = 0;
1008 mInfo.frameTop = 0;
1009 mInfo.frameRight = WIDTH;
1010 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001011 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001012 mInfo.globalScaleFactor = 1.0;
1013 mInfo.touchableRegion.clear();
1014 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001015 mInfo.ownerPid = WINDOW_PID;
1016 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001017 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001018 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001019 }
1020
Arthur Hungabbb9d82021-09-01 14:52:30 +00001021 sp<FakeWindowHandle> clone(
1022 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001023 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001024 sp<FakeWindowHandle> handle =
1025 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1026 displayId, mInfo.token);
1027 return handle;
1028 }
1029
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001030 void setTouchable(bool touchable) {
1031 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1032 }
chaviwd1c23182019-12-20 18:44:56 -08001033
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001034 void setFocusable(bool focusable) {
1035 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1036 }
1037
1038 void setVisible(bool visible) {
1039 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1040 }
Vishnu Nair958da932020-08-21 17:12:37 -07001041
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001042 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001043 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001044 }
1045
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001046 void setPaused(bool paused) {
1047 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1048 }
1049
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001050 void setPreventSplitting(bool preventSplitting) {
1051 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001052 }
1053
1054 void setSlippery(bool slippery) {
1055 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1056 }
1057
1058 void setWatchOutsideTouch(bool watchOutside) {
1059 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1060 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001061
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001062 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1063
1064 void setInterceptsStylus(bool interceptsStylus) {
1065 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1066 }
1067
1068 void setDropInput(bool dropInput) {
1069 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1070 }
1071
1072 void setDropInputIfObscured(bool dropInputIfObscured) {
1073 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1074 }
1075
1076 void setNoInputChannel(bool noInputChannel) {
1077 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1078 }
1079
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001080 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1081
chaviw3277faf2021-05-19 16:45:23 -05001082 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001083
Bernardo Rufino7393d172021-02-26 13:56:11 +00001084 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1085
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001086 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001087 mInfo.frameLeft = frame.left;
1088 mInfo.frameTop = frame.top;
1089 mInfo.frameRight = frame.right;
1090 mInfo.frameBottom = frame.bottom;
1091 mInfo.touchableRegion.clear();
1092 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001093
1094 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1095 ui::Transform translate;
1096 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1097 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001098 }
1099
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001100 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1101
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001102 void setIsWallpaper(bool isWallpaper) {
1103 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1104 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001105
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001106 void setDupTouchToWallpaper(bool hasWallpaper) {
1107 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1108 }
chaviwd1c23182019-12-20 18:44:56 -08001109
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001110 void setTrustedOverlay(bool trustedOverlay) {
1111 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1112 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001113
chaviw9eaa22c2020-07-01 16:21:27 -07001114 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1115 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1116 }
1117
1118 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001119
yunho.shinf4a80b82020-11-16 21:13:57 +09001120 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1121
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001122 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1123 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1124 expectedFlags);
1125 }
1126
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001127 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1128 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1129 }
1130
Svet Ganov5d3bc372020-01-26 23:11:07 -08001131 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001132 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001133 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1134 expectedFlags);
1135 }
1136
1137 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001138 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001139 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1140 expectedFlags);
1141 }
1142
1143 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001145 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1146 }
1147
1148 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1149 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001150 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1151 expectedFlags);
1152 }
1153
Svet Ganov5d3bc372020-01-26 23:11:07 -08001154 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001155 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1156 int32_t expectedFlags = 0) {
1157 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1158 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001159 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1160 }
1161
1162 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001163 int32_t expectedFlags = 0) {
1164 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1165 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001166 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1167 }
1168
1169 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001170 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001171 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1172 expectedFlags);
1173 }
1174
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001175 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1176 int32_t expectedFlags = 0) {
1177 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1178 expectedFlags);
1179 }
1180
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001181 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1182 int32_t expectedFlags = 0) {
1183 InputEvent* event = consume();
1184 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1185 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1186 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1187 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1188 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1189 }
1190
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001191 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1192 ASSERT_NE(mInputReceiver, nullptr)
1193 << "Cannot consume events from a window with no receiver";
1194 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1195 }
1196
Prabir Pradhan99987712020-11-10 18:43:05 -08001197 void consumeCaptureEvent(bool hasCapture) {
1198 ASSERT_NE(mInputReceiver, nullptr)
1199 << "Cannot consume events from a window with no receiver";
1200 mInputReceiver->consumeCaptureEvent(hasCapture);
1201 }
1202
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001203 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1204 std::optional<int32_t> expectedDisplayId,
1205 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001206 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1207 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1208 expectedFlags);
1209 }
1210
arthurhungb89ccb02020-12-30 16:19:01 +08001211 void consumeDragEvent(bool isExiting, float x, float y) {
1212 mInputReceiver->consumeDragEvent(isExiting, x, y);
1213 }
1214
Antonio Kantekf16f2832021-09-28 04:39:20 +00001215 void consumeTouchModeEvent(bool inTouchMode) {
1216 ASSERT_NE(mInputReceiver, nullptr)
1217 << "Cannot consume events from a window with no receiver";
1218 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1219 }
1220
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001221 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001222 if (mInputReceiver == nullptr) {
1223 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1224 return std::nullopt;
1225 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001227 }
1228
1229 void finishEvent(uint32_t sequenceNum) {
1230 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1231 mInputReceiver->finishEvent(sequenceNum);
1232 }
1233
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001234 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1235 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1236 mInputReceiver->sendTimeline(inputEventId, timeline);
1237 }
1238
chaviwaf87b3e2019-10-01 16:59:28 -07001239 InputEvent* consume() {
1240 if (mInputReceiver == nullptr) {
1241 return nullptr;
1242 }
1243 return mInputReceiver->consume();
1244 }
1245
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001246 MotionEvent* consumeMotion() {
1247 InputEvent* event = consume();
1248 if (event == nullptr) {
1249 ADD_FAILURE() << "Consume failed : no event";
1250 return nullptr;
1251 }
1252 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1253 ADD_FAILURE() << "Instead of motion event, got "
1254 << inputEventTypeToString(event->getType());
1255 return nullptr;
1256 }
1257 return static_cast<MotionEvent*>(event);
1258 }
1259
Arthur Hungb92218b2018-08-14 12:00:21 +08001260 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001261 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001262 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001263 return; // Can't receive events if the window does not have input channel
1264 }
1265 ASSERT_NE(nullptr, mInputReceiver)
1266 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001267 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001268 }
1269
chaviwaf87b3e2019-10-01 16:59:28 -07001270 sp<IBinder> getToken() { return mInfo.token; }
1271
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001272 const std::string& getName() { return mName; }
1273
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001274 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1275 mInfo.ownerPid = ownerPid;
1276 mInfo.ownerUid = ownerUid;
1277 }
1278
Prabir Pradhanedd96402022-02-15 01:46:16 -08001279 int32_t getPid() const { return mInfo.ownerPid; }
1280
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001281 void destroyReceiver() { mInputReceiver = nullptr; }
1282
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001283 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1284
chaviwd1c23182019-12-20 18:44:56 -08001285private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001286 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001287 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001288 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001289};
1290
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001291std::atomic<int32_t> FakeWindowHandle::sId{1};
1292
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001293static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001294 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 int32_t displayId = ADISPLAY_ID_NONE,
1296 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001297 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001298 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1299 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001300 KeyEvent event;
1301 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1302
1303 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001304 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001305 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1306 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001307
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001308 if (!allowKeyRepeat) {
1309 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1310 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001311 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001312 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001313}
1314
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001315static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001317 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1318}
1319
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001320// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1321// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1322// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001323static InputEventInjectionResult injectKeyDownNoRepeat(
1324 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001325 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1326 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1327 /* allowKeyRepeat */ false);
1328}
1329
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001330static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001331 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001332 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1333}
1334
Garfield Tandf26e862020-07-01 20:18:19 -07001335class PointerBuilder {
1336public:
1337 PointerBuilder(int32_t id, int32_t toolType) {
1338 mProperties.clear();
1339 mProperties.id = id;
1340 mProperties.toolType = toolType;
1341 mCoords.clear();
1342 }
1343
1344 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1345
1346 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1347
1348 PointerBuilder& axis(int32_t axis, float value) {
1349 mCoords.setAxisValue(axis, value);
1350 return *this;
1351 }
1352
1353 PointerProperties buildProperties() const { return mProperties; }
1354
1355 PointerCoords buildCoords() const { return mCoords; }
1356
1357private:
1358 PointerProperties mProperties;
1359 PointerCoords mCoords;
1360};
1361
1362class MotionEventBuilder {
1363public:
1364 MotionEventBuilder(int32_t action, int32_t source) {
1365 mAction = action;
1366 mSource = source;
1367 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1368 }
1369
1370 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1371 mEventTime = eventTime;
1372 return *this;
1373 }
1374
1375 MotionEventBuilder& displayId(int32_t displayId) {
1376 mDisplayId = displayId;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& actionButton(int32_t actionButton) {
1381 mActionButton = actionButton;
1382 return *this;
1383 }
1384
arthurhung6d4bed92021-03-17 11:59:33 +08001385 MotionEventBuilder& buttonState(int32_t buttonState) {
1386 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001387 return *this;
1388 }
1389
1390 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1391 mRawXCursorPosition = rawXCursorPosition;
1392 return *this;
1393 }
1394
1395 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1396 mRawYCursorPosition = rawYCursorPosition;
1397 return *this;
1398 }
1399
1400 MotionEventBuilder& pointer(PointerBuilder pointer) {
1401 mPointers.push_back(pointer);
1402 return *this;
1403 }
1404
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001405 MotionEventBuilder& addFlag(uint32_t flags) {
1406 mFlags |= flags;
1407 return *this;
1408 }
1409
Garfield Tandf26e862020-07-01 20:18:19 -07001410 MotionEvent build() {
1411 std::vector<PointerProperties> pointerProperties;
1412 std::vector<PointerCoords> pointerCoords;
1413 for (const PointerBuilder& pointer : mPointers) {
1414 pointerProperties.push_back(pointer.buildProperties());
1415 pointerCoords.push_back(pointer.buildCoords());
1416 }
1417
1418 // Set mouse cursor position for the most common cases to avoid boilerplate.
1419 if (mSource == AINPUT_SOURCE_MOUSE &&
1420 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1421 mPointers.size() == 1) {
1422 mRawXCursorPosition = pointerCoords[0].getX();
1423 mRawYCursorPosition = pointerCoords[0].getY();
1424 }
1425
1426 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001427 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001428 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001429 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001430 mButtonState, MotionClassification::NONE, identityTransform,
1431 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001432 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1433 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001434
1435 return event;
1436 }
1437
1438private:
1439 int32_t mAction;
1440 int32_t mSource;
1441 nsecs_t mEventTime;
1442 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1443 int32_t mActionButton{0};
1444 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001445 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001446 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1447 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1448
1449 std::vector<PointerBuilder> mPointers;
1450};
1451
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001452static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001454 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001455 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1456 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1457 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1458 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001459}
1460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001462 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001463 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001464 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1466 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001468 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1469 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001470 MotionEvent event = MotionEventBuilder(action, source)
1471 .displayId(displayId)
1472 .eventTime(eventTime)
1473 .rawXCursorPosition(cursorPosition.x)
1474 .rawYCursorPosition(cursorPosition.y)
1475 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1476 .x(position.x)
1477 .y(position.y))
1478 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001479
1480 // Inject event until dispatch out.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001481 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1482 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001483}
1484
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001485static InputEventInjectionResult injectMotionDown(
1486 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1487 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001488 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001489}
1490
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001491static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 int32_t source, int32_t displayId,
1493 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001494 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001495}
1496
Jackal Guof9696682018-10-05 12:23:23 +08001497static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1498 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1499 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001500 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1501 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1502 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001503
1504 return args;
1505}
1506
chaviwd1c23182019-12-20 18:44:56 -08001507static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1508 const std::vector<PointF>& points) {
1509 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001510 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1511 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1512 }
1513
chaviwd1c23182019-12-20 18:44:56 -08001514 PointerProperties pointerProperties[pointerCount];
1515 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001516
chaviwd1c23182019-12-20 18:44:56 -08001517 for (size_t i = 0; i < pointerCount; i++) {
1518 pointerProperties[i].clear();
1519 pointerProperties[i].id = i;
1520 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001521
chaviwd1c23182019-12-20 18:44:56 -08001522 pointerCoords[i].clear();
1523 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1524 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1525 }
Jackal Guof9696682018-10-05 12:23:23 +08001526
1527 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1528 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001529 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001530 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1531 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001532 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1533 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001534 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1535 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001536
1537 return args;
1538}
1539
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001540static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1541 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1542}
1543
chaviwd1c23182019-12-20 18:44:56 -08001544static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1545 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1546}
1547
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001548static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1549 const PointerCaptureRequest& request) {
1550 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001551}
1552
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001553/**
1554 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1555 * broken channel.
1556 */
1557TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1558 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1559 sp<FakeWindowHandle> window =
1560 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1561 ADISPLAY_ID_DEFAULT);
1562
1563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1564
1565 // Window closes its channel, but the window remains.
1566 window->destroyReceiver();
1567 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1568}
1569
Arthur Hungb92218b2018-08-14 12:00:21 +08001570TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001572 sp<FakeWindowHandle> window =
1573 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001574
Arthur Hung72d8dc32020-03-28 00:48:39 +00001575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1577 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001579
1580 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001581 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001582}
1583
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001584TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1586 sp<FakeWindowHandle> window =
1587 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1588
1589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1590 // Inject a MotionEvent to an unknown display.
1591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1594
1595 // Window should receive motion event.
1596 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1597}
1598
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001599/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001600 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001601 * This test serves as a sanity check for the next test, where setInputWindows is
1602 * called twice.
1603 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001604TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606 sp<FakeWindowHandle> window =
1607 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1608 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001609
1610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1613 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 // Window should receive motion event.
1617 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1618}
1619
1620/**
1621 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001622 */
1623TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001624 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001625 sp<FakeWindowHandle> window =
1626 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1627 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001628
1629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001632 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1633 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001635
1636 // Window should receive motion event.
1637 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1638}
1639
Arthur Hungb92218b2018-08-14 12:00:21 +08001640// The foreground window should receive the first touch down event.
1641TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001642 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001643 sp<FakeWindowHandle> windowTop =
1644 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1645 sp<FakeWindowHandle> windowSecond =
1646 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001647
Arthur Hung72d8dc32020-03-28 00:48:39 +00001648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1650 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001652
1653 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001654 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001655 windowSecond->assertNoEvents();
1656}
1657
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001658/**
1659 * Two windows: A top window, and a wallpaper behind the window.
1660 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1661 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001662 * 1. foregroundWindow <-- dup touch to wallpaper
1663 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001664 */
1665TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1667 sp<FakeWindowHandle> foregroundWindow =
1668 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001669 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001670 sp<FakeWindowHandle> wallpaperWindow =
1671 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001672 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001673 constexpr int expectedWallpaperFlags =
1674 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1675
1676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1678 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1679 {100, 200}))
1680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1681
1682 // Both foreground window and its wallpaper should receive the touch down
1683 foregroundWindow->consumeMotionDown();
1684 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1685
1686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1687 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1688 ADISPLAY_ID_DEFAULT, {110, 200}))
1689 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1690
1691 foregroundWindow->consumeMotionMove();
1692 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1693
1694 // Now the foreground window goes away, but the wallpaper stays
1695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1696 foregroundWindow->consumeMotionCancel();
1697 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1698 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1699}
1700
1701/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001702 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1703 * with the following differences:
1704 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1705 * clean up the connection.
1706 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1707 * Ensure that there's no crash in the dispatcher.
1708 */
1709TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1710 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1711 sp<FakeWindowHandle> foregroundWindow =
1712 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001713 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001714 sp<FakeWindowHandle> wallpaperWindow =
1715 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001716 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001717 constexpr int expectedWallpaperFlags =
1718 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1719
1720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1722 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1723 {100, 200}))
1724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1725
1726 // Both foreground window and its wallpaper should receive the touch down
1727 foregroundWindow->consumeMotionDown();
1728 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1729
1730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1731 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1732 ADISPLAY_ID_DEFAULT, {110, 200}))
1733 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1734
1735 foregroundWindow->consumeMotionMove();
1736 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1737
1738 // Wallpaper closes its channel, but the window remains.
1739 wallpaperWindow->destroyReceiver();
1740 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1741
1742 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1743 // is no longer valid.
1744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1745 foregroundWindow->consumeMotionCancel();
1746}
1747
1748/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001749 * A single window that receives touch (on top), and a wallpaper window underneath it.
1750 * The top window gets a multitouch gesture.
1751 * Ensure that wallpaper gets the same gesture.
1752 */
1753TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1754 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1755 sp<FakeWindowHandle> window =
1756 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001757 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001758
1759 sp<FakeWindowHandle> wallpaperWindow =
1760 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001761 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001762 constexpr int expectedWallpaperFlags =
1763 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1764
1765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1766
1767 // Touch down on top window
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1770 {100, 100}))
1771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1772
1773 // Both top window and its wallpaper should receive the touch down
1774 window->consumeMotionDown();
1775 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1776
1777 // Second finger down on the top window
1778 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001779 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001780 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1781 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1782 .x(100)
1783 .y(100))
1784 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1785 .x(150)
1786 .y(150))
1787 .build();
1788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1789 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1790 InputEventInjectionSync::WAIT_FOR_RESULT))
1791 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1792
1793 window->consumeMotionPointerDown(1 /* pointerIndex */);
1794 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1795 expectedWallpaperFlags);
1796 window->assertNoEvents();
1797 wallpaperWindow->assertNoEvents();
1798}
1799
1800/**
1801 * Two windows: a window on the left and window on the right.
1802 * A third window, wallpaper, is behind both windows, and spans both top windows.
1803 * The first touch down goes to the left window. A second pointer touches down on the right window.
1804 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1805 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1806 * ACTION_POINTER_DOWN(1).
1807 */
1808TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1809 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1810 sp<FakeWindowHandle> leftWindow =
1811 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1812 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001813 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001814
1815 sp<FakeWindowHandle> rightWindow =
1816 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1817 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001818 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001819
1820 sp<FakeWindowHandle> wallpaperWindow =
1821 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1822 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001823 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001824 constexpr int expectedWallpaperFlags =
1825 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1826
1827 mDispatcher->setInputWindows(
1828 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1829
1830 // Touch down on left window
1831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1832 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1833 {100, 100}))
1834 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1835
1836 // Both foreground window and its wallpaper should receive the touch down
1837 leftWindow->consumeMotionDown();
1838 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1839
1840 // Second finger down on the right window
1841 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001842 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001843 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1844 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1845 .x(100)
1846 .y(100))
1847 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1848 .x(300)
1849 .y(100))
1850 .build();
1851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1852 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1853 InputEventInjectionSync::WAIT_FOR_RESULT))
1854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1855
1856 leftWindow->consumeMotionMove();
1857 // Since the touch is split, right window gets ACTION_DOWN
1858 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1859 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1860 expectedWallpaperFlags);
1861
1862 // Now, leftWindow, which received the first finger, disappears.
1863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1864 leftWindow->consumeMotionCancel();
1865 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1866 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1867
1868 // The pointer that's still down on the right window moves, and goes to the right window only.
1869 // As far as the dispatcher's concerned though, both pointers are still present.
1870 const MotionEvent secondFingerMoveEvent =
1871 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1872 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1873 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1874 .x(100)
1875 .y(100))
1876 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1877 .x(310)
1878 .y(110))
1879 .build();
1880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1881 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1882 InputEventInjectionSync::WAIT_FOR_RESULT));
1883 rightWindow->consumeMotionMove();
1884
1885 leftWindow->assertNoEvents();
1886 rightWindow->assertNoEvents();
1887 wallpaperWindow->assertNoEvents();
1888}
1889
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001890/**
1891 * On the display, have a single window, and also an area where there's no window.
1892 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1893 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1894 */
1895TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1897 sp<FakeWindowHandle> window =
1898 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1899
1900 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1901 NotifyMotionArgs args;
1902
1903 // Touch down on the empty space
1904 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1905
1906 mDispatcher->waitForIdle();
1907 window->assertNoEvents();
1908
1909 // Now touch down on the window with another pointer
1910 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1911 mDispatcher->waitForIdle();
1912 window->consumeMotionDown();
1913}
1914
1915/**
1916 * Same test as above, but instead of touching the empty space, the first touch goes to
1917 * non-touchable window.
1918 */
1919TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1920 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1921 sp<FakeWindowHandle> window1 =
1922 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1923 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1924 window1->setTouchable(false);
1925 sp<FakeWindowHandle> window2 =
1926 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1927 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1928
1929 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1930
1931 NotifyMotionArgs args;
1932 // Touch down on the non-touchable window
1933 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1934
1935 mDispatcher->waitForIdle();
1936 window1->assertNoEvents();
1937 window2->assertNoEvents();
1938
1939 // Now touch down on the window with another pointer
1940 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1941 mDispatcher->waitForIdle();
1942 window2->consumeMotionDown();
1943}
1944
Garfield Tandf26e862020-07-01 20:18:19 -07001945TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001947 sp<FakeWindowHandle> windowLeft =
1948 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1949 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001950 sp<FakeWindowHandle> windowRight =
1951 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1952 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001953
1954 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1955
1956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1957
1958 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001960 injectMotionEvent(mDispatcher,
1961 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1962 AINPUT_SOURCE_MOUSE)
1963 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1964 .x(900)
1965 .y(400))
1966 .build()));
1967 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1968 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1969 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1970 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1971
1972 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001974 injectMotionEvent(mDispatcher,
1975 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1976 AINPUT_SOURCE_MOUSE)
1977 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1978 .x(300)
1979 .y(400))
1980 .build()));
1981 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1982 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1983 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1984 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1985 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1986 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1987
1988 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001990 injectMotionEvent(mDispatcher,
1991 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1992 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1993 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1994 .x(300)
1995 .y(400))
1996 .build()));
1997 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1998
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002000 injectMotionEvent(mDispatcher,
2001 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2002 AINPUT_SOURCE_MOUSE)
2003 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2004 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2005 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2006 .x(300)
2007 .y(400))
2008 .build()));
2009 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2010 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2011
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002013 injectMotionEvent(mDispatcher,
2014 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2015 AINPUT_SOURCE_MOUSE)
2016 .buttonState(0)
2017 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2018 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2019 .x(300)
2020 .y(400))
2021 .build()));
2022 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2023 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2024
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002026 injectMotionEvent(mDispatcher,
2027 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2028 .buttonState(0)
2029 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2030 .x(300)
2031 .y(400))
2032 .build()));
2033 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2034
2035 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002037 injectMotionEvent(mDispatcher,
2038 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2039 AINPUT_SOURCE_MOUSE)
2040 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2041 .x(900)
2042 .y(400))
2043 .build()));
2044 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2045 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2046 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2047 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2048 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2049 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2050}
2051
2052// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2053// directly in this test.
2054TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002055 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002056 sp<FakeWindowHandle> window =
2057 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2058 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002059
2060 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2061
2062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2063
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002065 injectMotionEvent(mDispatcher,
2066 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2067 AINPUT_SOURCE_MOUSE)
2068 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2069 .x(300)
2070 .y(400))
2071 .build()));
2072 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2073 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2074
2075 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002077 injectMotionEvent(mDispatcher,
2078 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2079 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2080 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2081 .x(300)
2082 .y(400))
2083 .build()));
2084 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2085
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002087 injectMotionEvent(mDispatcher,
2088 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2089 AINPUT_SOURCE_MOUSE)
2090 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2091 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2092 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2093 .x(300)
2094 .y(400))
2095 .build()));
2096 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2097 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2098
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002100 injectMotionEvent(mDispatcher,
2101 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2102 AINPUT_SOURCE_MOUSE)
2103 .buttonState(0)
2104 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2105 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2106 .x(300)
2107 .y(400))
2108 .build()));
2109 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2110 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2111
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002113 injectMotionEvent(mDispatcher,
2114 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2115 .buttonState(0)
2116 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2117 .x(300)
2118 .y(400))
2119 .build()));
2120 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2121
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002123 injectMotionEvent(mDispatcher,
2124 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2125 AINPUT_SOURCE_MOUSE)
2126 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2127 .x(300)
2128 .y(400))
2129 .build()));
2130 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2131 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2132}
2133
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02002134TEST_F(InputDispatcherTest, HoverEnterMoveRemoveWindowsInSecondDisplay) {
2135 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2136 sp<FakeWindowHandle> windowDefaultDisplay =
2137 sp<FakeWindowHandle>::make(application, mDispatcher, "DefaultDisplay",
2138 ADISPLAY_ID_DEFAULT);
2139 windowDefaultDisplay->setFrame(Rect(0, 0, 600, 800));
2140 sp<FakeWindowHandle> windowSecondDisplay =
2141 sp<FakeWindowHandle>::make(application, mDispatcher, "SecondDisplay",
2142 SECOND_DISPLAY_ID);
2143 windowSecondDisplay->setFrame(Rect(0, 0, 600, 800));
2144
2145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2146 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2147
2148 // Set cursor position in window in default display and check that hover enter and move
2149 // events are generated.
2150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2151 injectMotionEvent(mDispatcher,
2152 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2153 AINPUT_SOURCE_MOUSE)
2154 .displayId(ADISPLAY_ID_DEFAULT)
2155 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2156 .x(300)
2157 .y(600))
2158 .build()));
2159 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2160 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2161 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2162 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2163
2164 // Remove all windows in secondary display and check that no event happens on window in
2165 // primary display.
2166 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
2167 windowDefaultDisplay->assertNoEvents();
2168
2169 // Move cursor position in window in default display and check that only hover move
2170 // event is generated and not hover enter event.
2171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowDefaultDisplay}},
2172 {SECOND_DISPLAY_ID, {windowSecondDisplay}}});
2173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2174 injectMotionEvent(mDispatcher,
2175 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2176 AINPUT_SOURCE_MOUSE)
2177 .displayId(ADISPLAY_ID_DEFAULT)
2178 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2179 .x(400)
2180 .y(700))
2181 .build()));
2182 windowDefaultDisplay->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2183 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2184 windowDefaultDisplay->assertNoEvents();
2185}
2186
Garfield Tan00f511d2019-06-12 16:55:40 -07002187TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002188 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002189
2190 sp<FakeWindowHandle> windowLeft =
2191 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2192 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002193 sp<FakeWindowHandle> windowRight =
2194 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2195 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002196
2197 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2198
Arthur Hung72d8dc32020-03-28 00:48:39 +00002199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002200
2201 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2202 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002204 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002205 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002206 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002207 windowRight->assertNoEvents();
2208}
2209
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002210TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002211 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002212 sp<FakeWindowHandle> window =
2213 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002214 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002215
Arthur Hung72d8dc32020-03-28 00:48:39 +00002216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002217 setFocusedWindow(window);
2218
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002219 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002220
2221 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2222 mDispatcher->notifyKey(&keyArgs);
2223
2224 // Window should receive key down event.
2225 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2226
2227 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2228 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002229 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002230 mDispatcher->notifyDeviceReset(&args);
2231 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2232 AKEY_EVENT_FLAG_CANCELED);
2233}
2234
2235TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002236 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002237 sp<FakeWindowHandle> window =
2238 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2239
Arthur Hung72d8dc32020-03-28 00:48:39 +00002240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002241
2242 NotifyMotionArgs motionArgs =
2243 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2244 ADISPLAY_ID_DEFAULT);
2245 mDispatcher->notifyMotion(&motionArgs);
2246
2247 // Window should receive motion down event.
2248 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2249
2250 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2251 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002252 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002253 mDispatcher->notifyDeviceReset(&args);
2254 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2255 0 /*expectedFlags*/);
2256}
2257
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002258TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2260 sp<FakeWindowHandle> window =
2261 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2262 window->setFocusable(true);
2263
2264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2265 setFocusedWindow(window);
2266
2267 window->consumeFocusEvent(true);
2268
2269 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2270 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2271 const nsecs_t injectTime = keyArgs.eventTime;
2272 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2273 mDispatcher->notifyKey(&keyArgs);
2274 // The dispatching time should be always greater than or equal to intercept key timeout.
2275 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2276 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2277 std::chrono::nanoseconds(interceptKeyTimeout).count());
2278}
2279
2280TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2282 sp<FakeWindowHandle> window =
2283 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2284 window->setFocusable(true);
2285
2286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2287 setFocusedWindow(window);
2288
2289 window->consumeFocusEvent(true);
2290
2291 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2292 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2293 mFakePolicy->setInterceptKeyTimeout(150ms);
2294 mDispatcher->notifyKey(&keyDown);
2295 mDispatcher->notifyKey(&keyUp);
2296
2297 // Window should receive key event immediately when same key up.
2298 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2299 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2300}
2301
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002302/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002303 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2304 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2305 * ACTION_OUTSIDE event is sent per gesture.
2306 */
2307TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2308 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2310 sp<FakeWindowHandle> window =
2311 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2312 window->setWatchOutsideTouch(true);
2313 window->setFrame(Rect{0, 0, 100, 100});
2314 sp<FakeWindowHandle> secondWindow =
2315 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2316 secondWindow->setFrame(Rect{100, 100, 200, 200});
2317 sp<FakeWindowHandle> thirdWindow =
2318 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2319 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2321
2322 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2323 NotifyMotionArgs motionArgs =
2324 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2325 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2326 mDispatcher->notifyMotion(&motionArgs);
2327 window->assertNoEvents();
2328 secondWindow->assertNoEvents();
2329
2330 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2331 // Now, `window` should get ACTION_OUTSIDE.
2332 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2333 {PointF{-10, -10}, PointF{105, 105}});
2334 mDispatcher->notifyMotion(&motionArgs);
2335 window->consumeMotionOutside();
2336 secondWindow->consumeMotionDown();
2337 thirdWindow->assertNoEvents();
2338
2339 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2340 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2341 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2342 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2343 mDispatcher->notifyMotion(&motionArgs);
2344 window->assertNoEvents();
2345 secondWindow->consumeMotionMove();
2346 thirdWindow->consumeMotionDown();
2347}
2348
2349/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002350 * Ensure the correct coordinate spaces are used by InputDispatcher.
2351 *
2352 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2353 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2354 * space.
2355 */
2356class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2357public:
2358 void SetUp() override {
2359 InputDispatcherTest::SetUp();
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002360 removeAllWindowsAndDisplays();
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002361 }
2362
2363 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2364 gui::DisplayInfo info;
2365 info.displayId = displayId;
2366 info.transform = transform;
2367 mDisplayInfos.push_back(std::move(info));
2368 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2369 }
2370
2371 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2372 mWindowInfos.push_back(*windowHandle->getInfo());
2373 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2374 }
2375
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002376 void removeAllWindowsAndDisplays() {
2377 mDisplayInfos.clear();
2378 mWindowInfos.clear();
2379 }
2380
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002381 // Set up a test scenario where the display has a scaled projection and there are two windows
2382 // on the display.
2383 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2384 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2385 // respectively.
2386 ui::Transform displayTransform;
2387 displayTransform.set(2, 0, 0, 4);
2388 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2389
2390 std::shared_ptr<FakeApplicationHandle> application =
2391 std::make_shared<FakeApplicationHandle>();
2392
2393 // Add two windows to the display. Their frames are represented in the display space.
2394 sp<FakeWindowHandle> firstWindow =
2395 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002396 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2397 addWindow(firstWindow);
2398
2399 sp<FakeWindowHandle> secondWindow =
2400 new FakeWindowHandle(application, mDispatcher, "Second Window",
2401 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002402 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2403 addWindow(secondWindow);
2404 return {std::move(firstWindow), std::move(secondWindow)};
2405 }
2406
2407private:
2408 std::vector<gui::DisplayInfo> mDisplayInfos;
2409 std::vector<gui::WindowInfo> mWindowInfos;
2410};
2411
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002412TEST_F(InputDispatcherDisplayProjectionTest, HitTestCoordinateSpaceConsistency) {
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002413 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2414 // Send down to the first window. The point is represented in the display space. The point is
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002415 // selected so that if the hit test was performed with the point and the bounds being in
2416 // different coordinate spaces, the event would end up in the incorrect window.
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002417 NotifyMotionArgs downMotionArgs =
2418 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2419 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2420 mDispatcher->notifyMotion(&downMotionArgs);
2421
2422 firstWindow->consumeMotionDown();
2423 secondWindow->assertNoEvents();
2424}
2425
2426// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2427// the event should be treated as being in the logical display space.
2428TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2429 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2430 // Send down to the first window. The point is represented in the logical display space. The
2431 // point is selected so that if the hit test was done in logical display space, then it would
2432 // end up in the incorrect window.
2433 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2434 PointF{75 * 2, 55 * 4});
2435
2436 firstWindow->consumeMotionDown();
2437 secondWindow->assertNoEvents();
2438}
2439
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002440// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2441// event should be treated as being in the logical display space.
2442TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2443 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2444
2445 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2446 ui::Transform injectedEventTransform;
2447 injectedEventTransform.set(matrix);
2448 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2449 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2450
2451 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2452 .displayId(ADISPLAY_ID_DEFAULT)
2453 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2454 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2455 .x(untransformedPoint.x)
2456 .y(untransformedPoint.y))
2457 .build();
2458 event.transform(matrix);
2459
2460 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2461 InputEventInjectionSync::WAIT_FOR_RESULT);
2462
2463 firstWindow->consumeMotionDown();
2464 secondWindow->assertNoEvents();
2465}
2466
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002467TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2468 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2469
2470 // Send down to the second window.
2471 NotifyMotionArgs downMotionArgs =
2472 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2473 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2474 mDispatcher->notifyMotion(&downMotionArgs);
2475
2476 firstWindow->assertNoEvents();
2477 const MotionEvent* event = secondWindow->consumeMotion();
2478 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2479
2480 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2481 EXPECT_EQ(300, event->getRawX(0));
2482 EXPECT_EQ(880, event->getRawY(0));
2483
2484 // Ensure that the x and y values are in the window's coordinate space.
2485 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2486 // the logical display space. This will be the origin of the window space.
2487 EXPECT_EQ(100, event->getX(0));
2488 EXPECT_EQ(80, event->getY(0));
2489}
2490
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002491/** Ensure consistent behavior of InputDispatcher in all orientations. */
2492class InputDispatcherDisplayOrientationFixture
2493 : public InputDispatcherDisplayProjectionTest,
2494 public ::testing::WithParamInterface<ui::Rotation> {};
2495
2496// This test verifies the touchable region of a window for all rotations of the display by tapping
2497// in different locations on the display, specifically points close to the four corners of a
2498// window.
2499TEST_P(InputDispatcherDisplayOrientationFixture, HitTestInDifferentOrientations) {
2500 constexpr static int32_t displayWidth = 400;
2501 constexpr static int32_t displayHeight = 800;
2502
2503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2504
2505 const auto rotation = GetParam();
2506
2507 // Set up the display with the specified rotation.
2508 const bool isRotated = rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270;
2509 const int32_t logicalDisplayWidth = isRotated ? displayHeight : displayWidth;
2510 const int32_t logicalDisplayHeight = isRotated ? displayWidth : displayHeight;
2511 const ui::Transform displayTransform(ui::Transform::toRotationFlags(rotation),
2512 logicalDisplayWidth, logicalDisplayHeight);
2513 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2514
2515 // Create a window with its bounds determined in the logical display.
2516 const Rect frameInLogicalDisplay(100, 100, 200, 300);
2517 const Rect frameInDisplay = displayTransform.inverse().transform(frameInLogicalDisplay);
2518 sp<FakeWindowHandle> window =
2519 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2520 window->setFrame(frameInDisplay, displayTransform);
2521 addWindow(window);
2522
2523 // The following points in logical display space should be inside the window.
2524 static const std::array<vec2, 4> insidePoints{
2525 {{100, 100}, {199.99, 100}, {100, 299.99}, {199.99, 299.99}}};
2526 for (const auto pointInsideWindow : insidePoints) {
2527 const vec2 p = displayTransform.inverse().transform(pointInsideWindow);
2528 const PointF pointInDisplaySpace{p.x, p.y};
2529 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2530 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2531 mDispatcher->notifyMotion(&down);
2532 window->consumeMotionDown();
2533
2534 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2535 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2536 mDispatcher->notifyMotion(&up);
2537 window->consumeMotionUp();
2538 }
2539
2540 // The following points in logical display space should be outside the window.
2541 static const std::array<vec2, 5> outsidePoints{
2542 {{200, 100}, {100, 300}, {200, 300}, {100, 99.99}, {99.99, 100}}};
2543 for (const auto pointOutsideWindow : outsidePoints) {
2544 const vec2 p = displayTransform.inverse().transform(pointOutsideWindow);
2545 const PointF pointInDisplaySpace{p.x, p.y};
2546 const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2547 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2548 mDispatcher->notifyMotion(&down);
2549
2550 const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2551 ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
2552 mDispatcher->notifyMotion(&up);
2553 }
2554 window->assertNoEvents();
2555}
2556
2557// Run the precision tests for all rotations.
2558INSTANTIATE_TEST_SUITE_P(InputDispatcherDisplayOrientationTests,
2559 InputDispatcherDisplayOrientationFixture,
2560 ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
2561 ui::ROTATION_270));
2562
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002563using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2564 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002565
2566class TransferTouchFixture : public InputDispatcherTest,
2567 public ::testing::WithParamInterface<TransferFunction> {};
2568
2569TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002570 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002571
2572 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002573 sp<FakeWindowHandle> firstWindow =
2574 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2575 sp<FakeWindowHandle> secondWindow =
2576 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002577
2578 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002580
2581 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002582 NotifyMotionArgs downMotionArgs =
2583 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2584 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002585 mDispatcher->notifyMotion(&downMotionArgs);
2586 // Only the first window should get the down event
2587 firstWindow->consumeMotionDown();
2588 secondWindow->assertNoEvents();
2589
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002590 // Transfer touch to the second window
2591 TransferFunction f = GetParam();
2592 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2593 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002594 // The first window gets cancel and the second gets down
2595 firstWindow->consumeMotionCancel();
2596 secondWindow->consumeMotionDown();
2597
2598 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002599 NotifyMotionArgs upMotionArgs =
2600 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2601 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002602 mDispatcher->notifyMotion(&upMotionArgs);
2603 // The first window gets no events and the second gets up
2604 firstWindow->assertNoEvents();
2605 secondWindow->consumeMotionUp();
2606}
2607
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002608/**
2609 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2610 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2611 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2612 * natural to the user.
2613 * In this test, we are sending a pointer to both spy window and first window. We then try to
2614 * transfer touch to the second window. The dispatcher should identify the first window as the
2615 * one that should lose the gesture, and therefore the action should be to move the gesture from
2616 * the first window to the second.
2617 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2618 * the other API, as well.
2619 */
2620TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2622
2623 // Create a couple of windows + a spy window
2624 sp<FakeWindowHandle> spyWindow =
2625 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2626 spyWindow->setTrustedOverlay(true);
2627 spyWindow->setSpy(true);
2628 sp<FakeWindowHandle> firstWindow =
2629 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2630 sp<FakeWindowHandle> secondWindow =
2631 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2632
2633 // Add the windows to the dispatcher
2634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2635
2636 // Send down to the first window
2637 NotifyMotionArgs downMotionArgs =
2638 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2639 ADISPLAY_ID_DEFAULT);
2640 mDispatcher->notifyMotion(&downMotionArgs);
2641 // Only the first window and spy should get the down event
2642 spyWindow->consumeMotionDown();
2643 firstWindow->consumeMotionDown();
2644
2645 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2646 // if f === 'transferTouch'.
2647 TransferFunction f = GetParam();
2648 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2649 ASSERT_TRUE(success);
2650 // The first window gets cancel and the second gets down
2651 firstWindow->consumeMotionCancel();
2652 secondWindow->consumeMotionDown();
2653
2654 // Send up event to the second window
2655 NotifyMotionArgs upMotionArgs =
2656 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2657 ADISPLAY_ID_DEFAULT);
2658 mDispatcher->notifyMotion(&upMotionArgs);
2659 // The first window gets no events and the second+spy get up
2660 firstWindow->assertNoEvents();
2661 spyWindow->consumeMotionUp();
2662 secondWindow->consumeMotionUp();
2663}
2664
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002665TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002667
2668 PointF touchPoint = {10, 10};
2669
2670 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002671 sp<FakeWindowHandle> firstWindow =
2672 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002673 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002674 sp<FakeWindowHandle> secondWindow =
2675 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002676 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002677
2678 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002680
2681 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002682 NotifyMotionArgs downMotionArgs =
2683 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2684 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002685 mDispatcher->notifyMotion(&downMotionArgs);
2686 // Only the first window should get the down event
2687 firstWindow->consumeMotionDown();
2688 secondWindow->assertNoEvents();
2689
2690 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002691 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002692 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002693 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002694 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2695 // Only the first window should get the pointer down event
2696 firstWindow->consumeMotionPointerDown(1);
2697 secondWindow->assertNoEvents();
2698
2699 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002700 TransferFunction f = GetParam();
2701 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2702 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002703 // The first window gets cancel and the second gets down and pointer down
2704 firstWindow->consumeMotionCancel();
2705 secondWindow->consumeMotionDown();
2706 secondWindow->consumeMotionPointerDown(1);
2707
2708 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002709 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002710 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002711 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002712 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2713 // The first window gets nothing and the second gets pointer up
2714 firstWindow->assertNoEvents();
2715 secondWindow->consumeMotionPointerUp(1);
2716
2717 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002718 NotifyMotionArgs upMotionArgs =
2719 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2720 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002721 mDispatcher->notifyMotion(&upMotionArgs);
2722 // The first window gets nothing and the second gets up
2723 firstWindow->assertNoEvents();
2724 secondWindow->consumeMotionUp();
2725}
2726
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002727// For the cases of single pointer touch and two pointers non-split touch, the api's
2728// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2729// for the case where there are multiple pointers split across several windows.
2730INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2731 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002732 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2733 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002734 return dispatcher->transferTouch(destChannelToken,
2735 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002736 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002737 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2738 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002739 return dispatcher->transferTouchFocus(from, to,
2740 false /*isDragAndDrop*/);
2741 }));
2742
Svet Ganov5d3bc372020-01-26 23:11:07 -08002743TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002745
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002746 sp<FakeWindowHandle> firstWindow =
2747 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002748 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002749
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002750 sp<FakeWindowHandle> secondWindow =
2751 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002752 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002753
2754 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002756
2757 PointF pointInFirst = {300, 200};
2758 PointF pointInSecond = {300, 600};
2759
2760 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002761 NotifyMotionArgs firstDownMotionArgs =
2762 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2763 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002764 mDispatcher->notifyMotion(&firstDownMotionArgs);
2765 // Only the first window should get the down event
2766 firstWindow->consumeMotionDown();
2767 secondWindow->assertNoEvents();
2768
2769 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002770 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002771 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002772 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002773 mDispatcher->notifyMotion(&secondDownMotionArgs);
2774 // The first window gets a move and the second a down
2775 firstWindow->consumeMotionMove();
2776 secondWindow->consumeMotionDown();
2777
2778 // Transfer touch focus to the second window
2779 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2780 // The first window gets cancel and the new gets pointer down (it already saw down)
2781 firstWindow->consumeMotionCancel();
2782 secondWindow->consumeMotionPointerDown(1);
2783
2784 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002785 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002786 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002787 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002788 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2789 // The first window gets nothing and the second gets pointer up
2790 firstWindow->assertNoEvents();
2791 secondWindow->consumeMotionPointerUp(1);
2792
2793 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002794 NotifyMotionArgs upMotionArgs =
2795 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2796 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002797 mDispatcher->notifyMotion(&upMotionArgs);
2798 // The first window gets nothing and the second gets up
2799 firstWindow->assertNoEvents();
2800 secondWindow->consumeMotionUp();
2801}
2802
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002803// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2804// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2805// touch is not supported, so the touch should continue on those windows and the transferred-to
2806// window should get nothing.
2807TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2808 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2809
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002810 sp<FakeWindowHandle> firstWindow =
2811 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2812 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002813
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002814 sp<FakeWindowHandle> secondWindow =
2815 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2816 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002817
2818 // Add the windows to the dispatcher
2819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2820
2821 PointF pointInFirst = {300, 200};
2822 PointF pointInSecond = {300, 600};
2823
2824 // Send down to the first window
2825 NotifyMotionArgs firstDownMotionArgs =
2826 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2827 ADISPLAY_ID_DEFAULT, {pointInFirst});
2828 mDispatcher->notifyMotion(&firstDownMotionArgs);
2829 // Only the first window should get the down event
2830 firstWindow->consumeMotionDown();
2831 secondWindow->assertNoEvents();
2832
2833 // Send down to the second window
2834 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002835 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002836 {pointInFirst, pointInSecond});
2837 mDispatcher->notifyMotion(&secondDownMotionArgs);
2838 // The first window gets a move and the second a down
2839 firstWindow->consumeMotionMove();
2840 secondWindow->consumeMotionDown();
2841
2842 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002843 const bool transferred =
2844 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002845 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2846 ASSERT_FALSE(transferred);
2847 firstWindow->assertNoEvents();
2848 secondWindow->assertNoEvents();
2849
2850 // The rest of the dispatch should proceed as normal
2851 // Send pointer up to the second window
2852 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002853 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002854 {pointInFirst, pointInSecond});
2855 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2856 // The first window gets MOVE and the second gets pointer up
2857 firstWindow->consumeMotionMove();
2858 secondWindow->consumeMotionUp();
2859
2860 // Send up event to the first window
2861 NotifyMotionArgs upMotionArgs =
2862 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2863 ADISPLAY_ID_DEFAULT);
2864 mDispatcher->notifyMotion(&upMotionArgs);
2865 // The first window gets nothing and the second gets up
2866 firstWindow->consumeMotionUp();
2867 secondWindow->assertNoEvents();
2868}
2869
Arthur Hungabbb9d82021-09-01 14:52:30 +00002870// This case will create two windows and one mirrored window on the default display and mirror
2871// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2872// the windows info of second display before default display.
2873TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2875 sp<FakeWindowHandle> firstWindowInPrimary =
2876 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2877 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002878 sp<FakeWindowHandle> secondWindowInPrimary =
2879 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2880 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002881
2882 sp<FakeWindowHandle> mirrorWindowInPrimary =
2883 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2884 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002885
2886 sp<FakeWindowHandle> firstWindowInSecondary =
2887 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2888 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002889
2890 sp<FakeWindowHandle> secondWindowInSecondary =
2891 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2892 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002893
2894 // Update window info, let it find window handle of second display first.
2895 mDispatcher->setInputWindows(
2896 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2897 {ADISPLAY_ID_DEFAULT,
2898 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2899
2900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2902 {50, 50}))
2903 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2904
2905 // Window should receive motion event.
2906 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2907
2908 // Transfer touch focus
2909 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2910 secondWindowInPrimary->getToken()));
2911 // The first window gets cancel.
2912 firstWindowInPrimary->consumeMotionCancel();
2913 secondWindowInPrimary->consumeMotionDown();
2914
2915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2916 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2917 ADISPLAY_ID_DEFAULT, {150, 50}))
2918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2919 firstWindowInPrimary->assertNoEvents();
2920 secondWindowInPrimary->consumeMotionMove();
2921
2922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2923 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2924 {150, 50}))
2925 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2926 firstWindowInPrimary->assertNoEvents();
2927 secondWindowInPrimary->consumeMotionUp();
2928}
2929
2930// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2931// 'transferTouch' api.
2932TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2933 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2934 sp<FakeWindowHandle> firstWindowInPrimary =
2935 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2936 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002937 sp<FakeWindowHandle> secondWindowInPrimary =
2938 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2939 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002940
2941 sp<FakeWindowHandle> mirrorWindowInPrimary =
2942 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2943 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002944
2945 sp<FakeWindowHandle> firstWindowInSecondary =
2946 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2947 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002948
2949 sp<FakeWindowHandle> secondWindowInSecondary =
2950 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2951 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002952
2953 // Update window info, let it find window handle of second display first.
2954 mDispatcher->setInputWindows(
2955 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2956 {ADISPLAY_ID_DEFAULT,
2957 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2958
2959 // Touch on second display.
2960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2961 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2962 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2963
2964 // Window should receive motion event.
2965 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2966
2967 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002968 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002969
2970 // The first window gets cancel.
2971 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2972 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2973
2974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2976 SECOND_DISPLAY_ID, {150, 50}))
2977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2978 firstWindowInPrimary->assertNoEvents();
2979 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2980
2981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2982 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2983 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2984 firstWindowInPrimary->assertNoEvents();
2985 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2986}
2987
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002988TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002989 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002990 sp<FakeWindowHandle> window =
2991 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2992
Vishnu Nair47074b82020-08-14 11:54:47 -07002993 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002995 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002996
2997 window->consumeFocusEvent(true);
2998
2999 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3000 mDispatcher->notifyKey(&keyArgs);
3001
3002 // Window should receive key down event.
3003 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3004}
3005
3006TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003007 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003008 sp<FakeWindowHandle> window =
3009 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3010
Arthur Hung72d8dc32020-03-28 00:48:39 +00003011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012
3013 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3014 mDispatcher->notifyKey(&keyArgs);
3015 mDispatcher->waitForIdle();
3016
3017 window->assertNoEvents();
3018}
3019
3020// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3021TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003022 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003023 sp<FakeWindowHandle> window =
3024 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3025
Arthur Hung72d8dc32020-03-28 00:48:39 +00003026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003027
3028 // Send key
3029 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3030 mDispatcher->notifyKey(&keyArgs);
3031 // Send motion
3032 NotifyMotionArgs motionArgs =
3033 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3034 ADISPLAY_ID_DEFAULT);
3035 mDispatcher->notifyMotion(&motionArgs);
3036
3037 // Window should receive only the motion event
3038 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3039 window->assertNoEvents(); // Key event or focus event will not be received
3040}
3041
arthurhungea3f4fc2020-12-21 23:18:53 +08003042TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3044
arthurhungea3f4fc2020-12-21 23:18:53 +08003045 sp<FakeWindowHandle> firstWindow =
3046 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3047 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003048
arthurhungea3f4fc2020-12-21 23:18:53 +08003049 sp<FakeWindowHandle> secondWindow =
3050 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3051 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003052
3053 // Add the windows to the dispatcher
3054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3055
3056 PointF pointInFirst = {300, 200};
3057 PointF pointInSecond = {300, 600};
3058
3059 // Send down to the first window
3060 NotifyMotionArgs firstDownMotionArgs =
3061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3062 ADISPLAY_ID_DEFAULT, {pointInFirst});
3063 mDispatcher->notifyMotion(&firstDownMotionArgs);
3064 // Only the first window should get the down event
3065 firstWindow->consumeMotionDown();
3066 secondWindow->assertNoEvents();
3067
3068 // Send down to the second window
3069 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003070 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003071 {pointInFirst, pointInSecond});
3072 mDispatcher->notifyMotion(&secondDownMotionArgs);
3073 // The first window gets a move and the second a down
3074 firstWindow->consumeMotionMove();
3075 secondWindow->consumeMotionDown();
3076
3077 // Send pointer cancel to the second window
3078 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003079 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003080 {pointInFirst, pointInSecond});
3081 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3082 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3083 // The first window gets move and the second gets cancel.
3084 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3085 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3086
3087 // Send up event.
3088 NotifyMotionArgs upMotionArgs =
3089 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3090 ADISPLAY_ID_DEFAULT);
3091 mDispatcher->notifyMotion(&upMotionArgs);
3092 // The first window gets up and the second gets nothing.
3093 firstWindow->consumeMotionUp();
3094 secondWindow->assertNoEvents();
3095}
3096
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003097TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3098 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3099
3100 sp<FakeWindowHandle> window =
3101 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3103 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3104 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3105 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3106
3107 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3108 window->assertNoEvents();
3109 mDispatcher->waitForIdle();
3110}
3111
chaviwd1c23182019-12-20 18:44:56 -08003112class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003113public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003114 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003115 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003116 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003117 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003118 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003119 }
3120
chaviwd1c23182019-12-20 18:44:56 -08003121 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3122
3123 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3124 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3125 expectedDisplayId, expectedFlags);
3126 }
3127
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003128 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3129
3130 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3131
chaviwd1c23182019-12-20 18:44:56 -08003132 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3133 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3134 expectedDisplayId, expectedFlags);
3135 }
3136
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003137 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3138 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3139 expectedDisplayId, expectedFlags);
3140 }
3141
chaviwd1c23182019-12-20 18:44:56 -08003142 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3143 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3144 expectedDisplayId, expectedFlags);
3145 }
3146
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003147 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3148 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3149 expectedDisplayId, expectedFlags);
3150 }
3151
Arthur Hungfbfa5722021-11-16 02:45:54 +00003152 void consumeMotionPointerDown(int32_t pointerIdx) {
3153 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3154 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3155 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3156 0 /*expectedFlags*/);
3157 }
3158
Evan Rosky84f07f02021-04-16 10:42:42 -07003159 MotionEvent* consumeMotion() {
3160 InputEvent* event = mInputReceiver->consume();
3161 if (!event) {
3162 ADD_FAILURE() << "No event was produced";
3163 return nullptr;
3164 }
3165 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3166 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3167 return nullptr;
3168 }
3169 return static_cast<MotionEvent*>(event);
3170 }
3171
chaviwd1c23182019-12-20 18:44:56 -08003172 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3173
3174private:
3175 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003176};
3177
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003178using InputDispatcherMonitorTest = InputDispatcherTest;
3179
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003180/**
3181 * Two entities that receive touch: A window, and a global monitor.
3182 * The touch goes to the window, and then the window disappears.
3183 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3184 * for the monitor, as well.
3185 * 1. foregroundWindow
3186 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3187 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003188TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003189 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3190 sp<FakeWindowHandle> window =
3191 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3192
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003193 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003194
3195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3197 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3198 {100, 200}))
3199 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3200
3201 // Both the foreground window and the global monitor should receive the touch down
3202 window->consumeMotionDown();
3203 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3204
3205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3206 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3207 ADISPLAY_ID_DEFAULT, {110, 200}))
3208 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3209
3210 window->consumeMotionMove();
3211 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3212
3213 // Now the foreground window goes away
3214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3215 window->consumeMotionCancel();
3216 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3217
3218 // If more events come in, there will be no more foreground window to send them to. This will
3219 // cause a cancel for the monitor, as well.
3220 ASSERT_EQ(InputEventInjectionResult::FAILED,
3221 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3222 ADISPLAY_ID_DEFAULT, {120, 200}))
3223 << "Injection should fail because the window was removed";
3224 window->assertNoEvents();
3225 // Global monitor now gets the cancel
3226 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3227}
3228
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003229TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003230 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003231 sp<FakeWindowHandle> window =
3232 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003234
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003235 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003236
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003238 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003239 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003240 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003241 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003242}
3243
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003244TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3245 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003246
Chris Yea209fde2020-07-22 13:54:51 -07003247 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003248 sp<FakeWindowHandle> window =
3249 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003251
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003253 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003254 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003255 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003256 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003257
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003258 // Pilfer pointers from the monitor.
3259 // This should not do anything and the window should continue to receive events.
3260 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003261
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003263 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3264 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003265 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003266
3267 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3268 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003269}
3270
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003271TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003272 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3273 sp<FakeWindowHandle> window =
3274 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3276 window->setWindowOffset(20, 40);
3277 window->setWindowTransform(0, 1, -1, 0);
3278
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003279 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003280
3281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3282 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3283 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3284 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3285 MotionEvent* event = monitor.consumeMotion();
3286 // Even though window has transform, gesture monitor must not.
3287 ASSERT_EQ(ui::Transform(), event->getTransform());
3288}
3289
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003290TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003292 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003293
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003294 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003295 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003296 << "Injection should fail if there is a monitor, but no touchable window";
3297 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003298}
3299
chaviw81e2bb92019-12-18 15:03:51 -08003300TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003301 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003302 sp<FakeWindowHandle> window =
3303 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3304
Arthur Hung72d8dc32020-03-28 00:48:39 +00003305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003306
3307 NotifyMotionArgs motionArgs =
3308 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3309 ADISPLAY_ID_DEFAULT);
3310
3311 mDispatcher->notifyMotion(&motionArgs);
3312 // Window should receive motion down event.
3313 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3314
3315 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003316 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003317 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3318 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3319 motionArgs.pointerCoords[0].getX() - 10);
3320
3321 mDispatcher->notifyMotion(&motionArgs);
3322 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3323 0 /*expectedFlags*/);
3324}
3325
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003326/**
3327 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3328 * the device default right away. In the test scenario, we check both the default value,
3329 * and the action of enabling / disabling.
3330 */
3331TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003332 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003333 sp<FakeWindowHandle> window =
3334 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003335 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003336
3337 // Set focused application.
3338 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003339 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340
3341 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003343 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003344 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3345
3346 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003347 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003349 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3350
3351 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003352 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3353 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003354 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003355 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003357 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003358 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3359
3360 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003361 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003363 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3364
3365 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003366 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3367 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003368 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003369 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003371 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003372 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3373
3374 window->assertNoEvents();
3375}
3376
Gang Wange9087892020-01-07 12:17:14 -05003377TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003378 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003379 sp<FakeWindowHandle> window =
3380 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3381
3382 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003383 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003384
Arthur Hung72d8dc32020-03-28 00:48:39 +00003385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003386 setFocusedWindow(window);
3387
Gang Wange9087892020-01-07 12:17:14 -05003388 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3389
3390 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3391 mDispatcher->notifyKey(&keyArgs);
3392
3393 InputEvent* event = window->consume();
3394 ASSERT_NE(event, nullptr);
3395
3396 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3397 ASSERT_NE(verified, nullptr);
3398 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3399
3400 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3401 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3402 ASSERT_EQ(keyArgs.source, verified->source);
3403 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3404
3405 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3406
3407 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003408 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003409 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003410 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3411 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3412 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3413 ASSERT_EQ(0, verifiedKey.repeatCount);
3414}
3415
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003416TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003417 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003418 sp<FakeWindowHandle> window =
3419 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3420
3421 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3422
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003423 ui::Transform transform;
3424 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3425
3426 gui::DisplayInfo displayInfo;
3427 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3428 displayInfo.transform = transform;
3429
3430 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003431
3432 NotifyMotionArgs motionArgs =
3433 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3434 ADISPLAY_ID_DEFAULT);
3435 mDispatcher->notifyMotion(&motionArgs);
3436
3437 InputEvent* event = window->consume();
3438 ASSERT_NE(event, nullptr);
3439
3440 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3441 ASSERT_NE(verified, nullptr);
3442 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3443
3444 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3445 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3446 EXPECT_EQ(motionArgs.source, verified->source);
3447 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3448
3449 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3450
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003451 const vec2 rawXY =
3452 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3453 motionArgs.pointerCoords[0].getXYValue());
3454 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3455 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003456 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003457 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003458 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003459 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3460 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3461}
3462
chaviw09c8d2d2020-08-24 15:48:26 -07003463/**
3464 * Ensure that separate calls to sign the same data are generating the same key.
3465 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3466 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3467 * tests.
3468 */
3469TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3470 KeyEvent event = getTestKeyEvent();
3471 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3472
3473 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3474 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3475 ASSERT_EQ(hmac1, hmac2);
3476}
3477
3478/**
3479 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3480 */
3481TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3482 KeyEvent event = getTestKeyEvent();
3483 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3484 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3485
3486 verifiedEvent.deviceId += 1;
3487 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3488
3489 verifiedEvent.source += 1;
3490 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3491
3492 verifiedEvent.eventTimeNanos += 1;
3493 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3494
3495 verifiedEvent.displayId += 1;
3496 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3497
3498 verifiedEvent.action += 1;
3499 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3500
3501 verifiedEvent.downTimeNanos += 1;
3502 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3503
3504 verifiedEvent.flags += 1;
3505 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3506
3507 verifiedEvent.keyCode += 1;
3508 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3509
3510 verifiedEvent.scanCode += 1;
3511 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3512
3513 verifiedEvent.metaState += 1;
3514 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3515
3516 verifiedEvent.repeatCount += 1;
3517 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3518}
3519
Vishnu Nair958da932020-08-21 17:12:37 -07003520TEST_F(InputDispatcherTest, SetFocusedWindow) {
3521 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3522 sp<FakeWindowHandle> windowTop =
3523 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3524 sp<FakeWindowHandle> windowSecond =
3525 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3526 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3527
3528 // Top window is also focusable but is not granted focus.
3529 windowTop->setFocusable(true);
3530 windowSecond->setFocusable(true);
3531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3532 setFocusedWindow(windowSecond);
3533
3534 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003535 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3536 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003537
3538 // Focused window should receive event.
3539 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3540 windowTop->assertNoEvents();
3541}
3542
3543TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3544 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3545 sp<FakeWindowHandle> window =
3546 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3547 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3548
3549 window->setFocusable(true);
3550 // Release channel for window is no longer valid.
3551 window->releaseChannel();
3552 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3553 setFocusedWindow(window);
3554
3555 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003556 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3557 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003558
3559 // window channel is invalid, so it should not receive any input event.
3560 window->assertNoEvents();
3561}
3562
3563TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3565 sp<FakeWindowHandle> window =
3566 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003567 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003568 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3569
Vishnu Nair958da932020-08-21 17:12:37 -07003570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3571 setFocusedWindow(window);
3572
3573 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003574 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3575 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003576
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003577 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003578 window->assertNoEvents();
3579}
3580
3581TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3582 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3583 sp<FakeWindowHandle> windowTop =
3584 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3585 sp<FakeWindowHandle> windowSecond =
3586 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3587 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3588
3589 windowTop->setFocusable(true);
3590 windowSecond->setFocusable(true);
3591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3592 setFocusedWindow(windowTop);
3593 windowTop->consumeFocusEvent(true);
3594
3595 setFocusedWindow(windowSecond, windowTop);
3596 windowSecond->consumeFocusEvent(true);
3597 windowTop->consumeFocusEvent(false);
3598
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3600 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003601
3602 // Focused window should receive event.
3603 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3604}
3605
3606TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3607 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3608 sp<FakeWindowHandle> windowTop =
3609 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3610 sp<FakeWindowHandle> windowSecond =
3611 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3613
3614 windowTop->setFocusable(true);
3615 windowSecond->setFocusable(true);
3616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3617 setFocusedWindow(windowSecond, windowTop);
3618
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003619 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3620 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003621
3622 // Event should be dropped.
3623 windowTop->assertNoEvents();
3624 windowSecond->assertNoEvents();
3625}
3626
3627TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3628 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3629 sp<FakeWindowHandle> window =
3630 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3631 sp<FakeWindowHandle> previousFocusedWindow =
3632 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3633 ADISPLAY_ID_DEFAULT);
3634 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3635
3636 window->setFocusable(true);
3637 previousFocusedWindow->setFocusable(true);
3638 window->setVisible(false);
3639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3640 setFocusedWindow(previousFocusedWindow);
3641 previousFocusedWindow->consumeFocusEvent(true);
3642
3643 // Requesting focus on invisible window takes focus from currently focused window.
3644 setFocusedWindow(window);
3645 previousFocusedWindow->consumeFocusEvent(false);
3646
3647 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003649 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003650 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003651
3652 // Window does not get focus event or key down.
3653 window->assertNoEvents();
3654
3655 // Window becomes visible.
3656 window->setVisible(true);
3657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3658
3659 // Window receives focus event.
3660 window->consumeFocusEvent(true);
3661 // Focused window receives key down.
3662 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3663}
3664
Vishnu Nair599f1412021-06-21 10:39:58 -07003665TEST_F(InputDispatcherTest, DisplayRemoved) {
3666 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3667 sp<FakeWindowHandle> window =
3668 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3669 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3670
3671 // window is granted focus.
3672 window->setFocusable(true);
3673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3674 setFocusedWindow(window);
3675 window->consumeFocusEvent(true);
3676
3677 // When a display is removed window loses focus.
3678 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3679 window->consumeFocusEvent(false);
3680}
3681
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003682/**
3683 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3684 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3685 * of the 'slipperyEnterWindow'.
3686 *
3687 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3688 * a way so that the touched location is no longer covered by the top window.
3689 *
3690 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3691 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3692 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3693 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3694 * with ACTION_DOWN).
3695 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3696 * window moved itself away from the touched location and had Flag::SLIPPERY.
3697 *
3698 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3699 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3700 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3701 *
3702 * In this test, we ensure that the event received by the bottom window has
3703 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3704 */
3705TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00003706 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3707 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003708
3709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3710 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3711
3712 sp<FakeWindowHandle> slipperyExitWindow =
3713 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003714 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003715 // Make sure this one overlaps the bottom window
3716 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3717 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3718 // one. Windows with the same owner are not considered to be occluding each other.
3719 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3720
3721 sp<FakeWindowHandle> slipperyEnterWindow =
3722 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3723 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3724
3725 mDispatcher->setInputWindows(
3726 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3727
3728 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3729 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3730 ADISPLAY_ID_DEFAULT, {{50, 50}});
3731 mDispatcher->notifyMotion(&args);
3732 slipperyExitWindow->consumeMotionDown();
3733 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3734 mDispatcher->setInputWindows(
3735 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3736
3737 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3738 ADISPLAY_ID_DEFAULT, {{51, 51}});
3739 mDispatcher->notifyMotion(&args);
3740
3741 slipperyExitWindow->consumeMotionCancel();
3742
3743 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3744 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3745}
3746
Garfield Tan1c7bc862020-01-28 13:24:04 -08003747class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3748protected:
3749 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3750 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3751
Chris Yea209fde2020-07-22 13:54:51 -07003752 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003753 sp<FakeWindowHandle> mWindow;
3754
3755 virtual void SetUp() override {
3756 mFakePolicy = new FakeInputDispatcherPolicy();
3757 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003758 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003759 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3760 ASSERT_EQ(OK, mDispatcher->start());
3761
3762 setUpWindow();
3763 }
3764
3765 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003766 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003767 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3768
Vishnu Nair47074b82020-08-14 11:54:47 -07003769 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003771 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003772 mWindow->consumeFocusEvent(true);
3773 }
3774
Chris Ye2ad95392020-09-01 13:44:44 -07003775 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003776 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003777 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003778 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3779 mDispatcher->notifyKey(&keyArgs);
3780
3781 // Window should receive key down event.
3782 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3783 }
3784
3785 void expectKeyRepeatOnce(int32_t repeatCount) {
3786 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3787 InputEvent* repeatEvent = mWindow->consume();
3788 ASSERT_NE(nullptr, repeatEvent);
3789
3790 uint32_t eventType = repeatEvent->getType();
3791 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3792
3793 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3794 uint32_t eventAction = repeatKeyEvent->getAction();
3795 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3796 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3797 }
3798
Chris Ye2ad95392020-09-01 13:44:44 -07003799 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003800 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003801 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003802 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3803 mDispatcher->notifyKey(&keyArgs);
3804
3805 // Window should receive key down event.
3806 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3807 0 /*expectedFlags*/);
3808 }
3809};
3810
3811TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003812 sendAndConsumeKeyDown(1 /* deviceId */);
3813 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3814 expectKeyRepeatOnce(repeatCount);
3815 }
3816}
3817
3818TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3819 sendAndConsumeKeyDown(1 /* deviceId */);
3820 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3821 expectKeyRepeatOnce(repeatCount);
3822 }
3823 sendAndConsumeKeyDown(2 /* deviceId */);
3824 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003825 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3826 expectKeyRepeatOnce(repeatCount);
3827 }
3828}
3829
3830TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003831 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003832 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003833 sendAndConsumeKeyUp(1 /* deviceId */);
3834 mWindow->assertNoEvents();
3835}
3836
3837TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3838 sendAndConsumeKeyDown(1 /* deviceId */);
3839 expectKeyRepeatOnce(1 /*repeatCount*/);
3840 sendAndConsumeKeyDown(2 /* deviceId */);
3841 expectKeyRepeatOnce(1 /*repeatCount*/);
3842 // Stale key up from device 1.
3843 sendAndConsumeKeyUp(1 /* deviceId */);
3844 // Device 2 is still down, keep repeating
3845 expectKeyRepeatOnce(2 /*repeatCount*/);
3846 expectKeyRepeatOnce(3 /*repeatCount*/);
3847 // Device 2 key up
3848 sendAndConsumeKeyUp(2 /* deviceId */);
3849 mWindow->assertNoEvents();
3850}
3851
3852TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3853 sendAndConsumeKeyDown(1 /* deviceId */);
3854 expectKeyRepeatOnce(1 /*repeatCount*/);
3855 sendAndConsumeKeyDown(2 /* deviceId */);
3856 expectKeyRepeatOnce(1 /*repeatCount*/);
3857 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3858 sendAndConsumeKeyUp(2 /* deviceId */);
3859 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003860 mWindow->assertNoEvents();
3861}
3862
liushenxiang42232912021-05-21 20:24:09 +08003863TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3864 sendAndConsumeKeyDown(DEVICE_ID);
3865 expectKeyRepeatOnce(1 /*repeatCount*/);
3866 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3867 mDispatcher->notifyDeviceReset(&args);
3868 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3869 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3870 mWindow->assertNoEvents();
3871}
3872
Garfield Tan1c7bc862020-01-28 13:24:04 -08003873TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003874 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003875 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3876 InputEvent* repeatEvent = mWindow->consume();
3877 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3878 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3879 IdGenerator::getSource(repeatEvent->getId()));
3880 }
3881}
3882
3883TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003884 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003885
3886 std::unordered_set<int32_t> idSet;
3887 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3888 InputEvent* repeatEvent = mWindow->consume();
3889 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3890 int32_t id = repeatEvent->getId();
3891 EXPECT_EQ(idSet.end(), idSet.find(id));
3892 idSet.insert(id);
3893 }
3894}
3895
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003896/* Test InputDispatcher for MultiDisplay */
3897class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3898public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003899 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003900 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003901
Chris Yea209fde2020-07-22 13:54:51 -07003902 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003903 windowInPrimary =
3904 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003905
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003906 // Set focus window for primary display, but focused display would be second one.
3907 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003908 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003910 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003911 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003912
Chris Yea209fde2020-07-22 13:54:51 -07003913 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003914 windowInSecondary =
3915 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003916 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003917 // Set focus display to second one.
3918 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3919 // Set focus window for second display.
3920 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003921 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003922 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003923 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003924 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003925 }
3926
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003927 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003928 InputDispatcherTest::TearDown();
3929
Chris Yea209fde2020-07-22 13:54:51 -07003930 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003931 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003932 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003933 windowInSecondary.clear();
3934 }
3935
3936protected:
Chris Yea209fde2020-07-22 13:54:51 -07003937 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003938 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003939 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003940 sp<FakeWindowHandle> windowInSecondary;
3941};
3942
3943TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3944 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003948 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003949 windowInSecondary->assertNoEvents();
3950
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003951 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003955 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003956 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003957}
3958
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003959TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003960 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3962 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003963 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003964 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003965 windowInSecondary->assertNoEvents();
3966
3967 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003969 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003970 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003971 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003972
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003973 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003974 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003976 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003977 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3978 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003979
3980 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003981 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003982 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003983 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003984 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003985 windowInSecondary->assertNoEvents();
3986}
3987
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003988// Test per-display input monitors for motion event.
3989TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003990 FakeMonitorReceiver monitorInPrimary =
3991 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3992 FakeMonitorReceiver monitorInSecondary =
3993 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003994
3995 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3998 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003999 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004000 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004001 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004002 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004003
4004 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4006 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004008 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004009 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004010 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004011 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004012
4013 // Test inject a non-pointer motion event.
4014 // If specific a display, it will dispatch to the focused window of particular display,
4015 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4017 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004019 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004020 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004021 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004022 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004023}
4024
4025// Test per-display input monitors for key event.
4026TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004027 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004028 FakeMonitorReceiver monitorInPrimary =
4029 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4030 FakeMonitorReceiver monitorInSecondary =
4031 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004032
4033 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4035 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004036 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004037 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004038 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004039 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004040}
4041
Vishnu Nair958da932020-08-21 17:12:37 -07004042TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4043 sp<FakeWindowHandle> secondWindowInPrimary =
4044 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
4045 secondWindowInPrimary->setFocusable(true);
4046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4047 setFocusedWindow(secondWindowInPrimary);
4048 windowInPrimary->consumeFocusEvent(false);
4049 secondWindowInPrimary->consumeFocusEvent(true);
4050
4051 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4053 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004054 windowInPrimary->assertNoEvents();
4055 windowInSecondary->assertNoEvents();
4056 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4057}
4058
Arthur Hungdfd528e2021-12-08 13:23:04 +00004059TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4060 FakeMonitorReceiver monitorInPrimary =
4061 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4062 FakeMonitorReceiver monitorInSecondary =
4063 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4064
4065 // Test touch down on primary display.
4066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4067 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4068 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4069 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4070 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4071
4072 // Test touch down on second display.
4073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4074 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4075 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4076 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4077 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4078
4079 // Trigger cancel touch.
4080 mDispatcher->cancelCurrentTouch();
4081 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4082 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4083 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4084 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4085
4086 // Test inject a move motion event, no window/monitor should receive the event.
4087 ASSERT_EQ(InputEventInjectionResult::FAILED,
4088 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4089 ADISPLAY_ID_DEFAULT, {110, 200}))
4090 << "Inject motion event should return InputEventInjectionResult::FAILED";
4091 windowInPrimary->assertNoEvents();
4092 monitorInPrimary.assertNoEvents();
4093
4094 ASSERT_EQ(InputEventInjectionResult::FAILED,
4095 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4096 SECOND_DISPLAY_ID, {110, 200}))
4097 << "Inject motion event should return InputEventInjectionResult::FAILED";
4098 windowInSecondary->assertNoEvents();
4099 monitorInSecondary.assertNoEvents();
4100}
4101
Jackal Guof9696682018-10-05 12:23:23 +08004102class InputFilterTest : public InputDispatcherTest {
4103protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004104 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4105 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004106 NotifyMotionArgs motionArgs;
4107
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004108 motionArgs =
4109 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004110 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004111 motionArgs =
4112 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004113 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004114 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004115 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004116 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4117 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004118 } else {
4119 mFakePolicy->assertFilterInputEventWasNotCalled();
4120 }
4121 }
4122
4123 void testNotifyKey(bool expectToBeFiltered) {
4124 NotifyKeyArgs keyArgs;
4125
4126 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4127 mDispatcher->notifyKey(&keyArgs);
4128 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4129 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004130 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004131
4132 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004133 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004134 } else {
4135 mFakePolicy->assertFilterInputEventWasNotCalled();
4136 }
4137 }
4138};
4139
4140// Test InputFilter for MotionEvent
4141TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4142 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4143 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4144 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4145
4146 // Enable InputFilter
4147 mDispatcher->setInputFilterEnabled(true);
4148 // Test touch on both primary and second display, and check if both events are filtered.
4149 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4150 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4151
4152 // Disable InputFilter
4153 mDispatcher->setInputFilterEnabled(false);
4154 // Test touch on both primary and second display, and check if both events aren't filtered.
4155 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4156 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4157}
4158
4159// Test InputFilter for KeyEvent
4160TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4161 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4162 testNotifyKey(/*expectToBeFiltered*/ false);
4163
4164 // Enable InputFilter
4165 mDispatcher->setInputFilterEnabled(true);
4166 // Send a key event, and check if it is filtered.
4167 testNotifyKey(/*expectToBeFiltered*/ true);
4168
4169 // Disable InputFilter
4170 mDispatcher->setInputFilterEnabled(false);
4171 // Send a key event, and check if it isn't filtered.
4172 testNotifyKey(/*expectToBeFiltered*/ false);
4173}
4174
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004175// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4176// logical display coordinate space.
4177TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4178 ui::Transform firstDisplayTransform;
4179 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4180 ui::Transform secondDisplayTransform;
4181 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4182
4183 std::vector<gui::DisplayInfo> displayInfos(2);
4184 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4185 displayInfos[0].transform = firstDisplayTransform;
4186 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4187 displayInfos[1].transform = secondDisplayTransform;
4188
4189 mDispatcher->onWindowInfosChanged({}, displayInfos);
4190
4191 // Enable InputFilter
4192 mDispatcher->setInputFilterEnabled(true);
4193
4194 // Ensure the correct transforms are used for the displays.
4195 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4196 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4197}
4198
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4200protected:
4201 virtual void SetUp() override {
4202 InputDispatcherTest::SetUp();
4203
4204 /**
4205 * We don't need to enable input filter to test the injected event policy, but we enabled it
4206 * here to make the tests more realistic, since this policy only matters when inputfilter is
4207 * on.
4208 */
4209 mDispatcher->setInputFilterEnabled(true);
4210
4211 std::shared_ptr<InputApplicationHandle> application =
4212 std::make_shared<FakeApplicationHandle>();
4213 mWindow =
4214 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4215
4216 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4217 mWindow->setFocusable(true);
4218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4219 setFocusedWindow(mWindow);
4220 mWindow->consumeFocusEvent(true);
4221 }
4222
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4224 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004225 KeyEvent event;
4226
4227 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4228 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4229 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4230 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4231 const int32_t additionalPolicyFlags =
4232 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004234 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4236 policyFlags | additionalPolicyFlags));
4237
4238 InputEvent* received = mWindow->consume();
4239 ASSERT_NE(nullptr, received);
4240 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4242 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4243 ASSERT_EQ(flags, keyEvent.getFlags());
4244 }
4245
4246 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4247 int32_t flags) {
4248 MotionEvent event;
4249 PointerProperties pointerProperties[1];
4250 PointerCoords pointerCoords[1];
4251 pointerProperties[0].clear();
4252 pointerProperties[0].id = 0;
4253 pointerCoords[0].clear();
4254 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4255 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4256
4257 ui::Transform identityTransform;
4258 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4259 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4260 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4261 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4262 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004263 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004264 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004265 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4266
4267 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004269 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004270 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4271 policyFlags | additionalPolicyFlags));
4272
4273 InputEvent* received = mWindow->consume();
4274 ASSERT_NE(nullptr, received);
4275 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4276 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4277 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4278 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 }
4280
4281private:
4282 sp<FakeWindowHandle> mWindow;
4283};
4284
4285TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004286 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4287 // filter. Without it, the event will no different from a regularly injected event, and the
4288 // injected device id will be overwritten.
4289 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4290 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004291}
4292
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004293TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004295 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4296 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4297}
4298
4299TEST_F(InputFilterInjectionPolicyTest,
4300 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4301 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4302 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4303 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004304}
4305
4306TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4307 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004308 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004309}
4310
chaviwfd6d3512019-03-25 13:23:49 -07004311class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004312 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004313 InputDispatcherTest::SetUp();
4314
Chris Yea209fde2020-07-22 13:54:51 -07004315 std::shared_ptr<FakeApplicationHandle> application =
4316 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004317 mUnfocusedWindow =
4318 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004319 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004320
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004321 mFocusedWindow =
4322 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4323 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004324
4325 // Set focused application.
4326 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004327 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004328
4329 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004331 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004332 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004333 }
4334
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004335 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004336 InputDispatcherTest::TearDown();
4337
4338 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004339 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004340 }
4341
4342protected:
4343 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004344 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004345 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004346};
4347
4348// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4349// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4350// the onPointerDownOutsideFocus callback.
4351TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004352 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004353 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4354 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004356 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004357
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004358 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004359 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4360}
4361
4362// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4363// DOWN on the window that doesn't have focus. Ensure no window received the
4364// onPointerDownOutsideFocus callback.
4365TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004367 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004369 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004370
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004371 ASSERT_TRUE(mDispatcher->waitForIdle());
4372 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004373}
4374
4375// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4376// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4377TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4379 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004380 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004381 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004382
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004383 ASSERT_TRUE(mDispatcher->waitForIdle());
4384 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004385}
4386
4387// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4388// DOWN on the window that already has focus. Ensure no window received the
4389// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004390TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004392 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004393 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004394 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004395 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004396
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004397 ASSERT_TRUE(mDispatcher->waitForIdle());
4398 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004399}
4400
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004401// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4402// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4403TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4404 const MotionEvent event =
4405 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4406 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4407 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4408 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4409 .build();
4410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4412 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4413
4414 ASSERT_TRUE(mDispatcher->waitForIdle());
4415 mFakePolicy->assertOnPointerDownWasNotCalled();
4416 // Ensure that the unfocused window did not receive any FOCUS events.
4417 mUnfocusedWindow->assertNoEvents();
4418}
4419
chaviwaf87b3e2019-10-01 16:59:28 -07004420// These tests ensures we can send touch events to a single client when there are multiple input
4421// windows that point to the same client token.
4422class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4423 virtual void SetUp() override {
4424 InputDispatcherTest::SetUp();
4425
Chris Yea209fde2020-07-22 13:54:51 -07004426 std::shared_ptr<FakeApplicationHandle> application =
4427 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004428 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4429 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004430 mWindow1->setFrame(Rect(0, 0, 100, 100));
4431
4432 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4433 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004434 mWindow2->setFrame(Rect(100, 100, 200, 200));
4435
Arthur Hung72d8dc32020-03-28 00:48:39 +00004436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004437 }
4438
4439protected:
4440 sp<FakeWindowHandle> mWindow1;
4441 sp<FakeWindowHandle> mWindow2;
4442
4443 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004444 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004445 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4446 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004447 }
4448
4449 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4450 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004451 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004452 InputEvent* event = window->consume();
4453
4454 ASSERT_NE(nullptr, event) << name.c_str()
4455 << ": consumer should have returned non-NULL event.";
4456
4457 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4458 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4459 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4460
4461 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004462 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004463
4464 for (size_t i = 0; i < points.size(); i++) {
4465 float expectedX = points[i].x;
4466 float expectedY = points[i].y;
4467
4468 EXPECT_EQ(expectedX, motionEvent.getX(i))
4469 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4470 << ", got " << motionEvent.getX(i);
4471 EXPECT_EQ(expectedY, motionEvent.getY(i))
4472 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4473 << ", got " << motionEvent.getY(i);
4474 }
4475 }
chaviw9eaa22c2020-07-01 16:21:27 -07004476
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004477 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004478 std::vector<PointF> expectedPoints) {
4479 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4480 ADISPLAY_ID_DEFAULT, touchedPoints);
4481 mDispatcher->notifyMotion(&motionArgs);
4482
4483 // Always consume from window1 since it's the window that has the InputReceiver
4484 consumeMotionEvent(mWindow1, action, expectedPoints);
4485 }
chaviwaf87b3e2019-10-01 16:59:28 -07004486};
4487
4488TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4489 // Touch Window 1
4490 PointF touchedPoint = {10, 10};
4491 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004492 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004493
4494 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004495 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004496
4497 // Touch Window 2
4498 touchedPoint = {150, 150};
4499 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004500 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004501}
4502
chaviw9eaa22c2020-07-01 16:21:27 -07004503TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4504 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004505 mWindow2->setWindowScale(0.5f, 0.5f);
4506
4507 // Touch Window 1
4508 PointF touchedPoint = {10, 10};
4509 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004510 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004511 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004512 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004513
4514 // Touch Window 2
4515 touchedPoint = {150, 150};
4516 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004517 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4518 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004519
chaviw9eaa22c2020-07-01 16:21:27 -07004520 // Update the transform so rotation is set
4521 mWindow2->setWindowTransform(0, -1, 1, 0);
4522 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4523 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004524}
4525
chaviw9eaa22c2020-07-01 16:21:27 -07004526TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004527 mWindow2->setWindowScale(0.5f, 0.5f);
4528
4529 // Touch Window 1
4530 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4531 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004532 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004533
4534 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004535 touchedPoints.push_back(PointF{150, 150});
4536 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004537 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004538
chaviw9eaa22c2020-07-01 16:21:27 -07004539 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004540 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004541 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004542
chaviw9eaa22c2020-07-01 16:21:27 -07004543 // Update the transform so rotation is set for Window 2
4544 mWindow2->setWindowTransform(0, -1, 1, 0);
4545 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004546 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004547}
4548
chaviw9eaa22c2020-07-01 16:21:27 -07004549TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004550 mWindow2->setWindowScale(0.5f, 0.5f);
4551
4552 // Touch Window 1
4553 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4554 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004555 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004556
4557 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004558 touchedPoints.push_back(PointF{150, 150});
4559 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004560
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004561 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004562
4563 // Move both windows
4564 touchedPoints = {{20, 20}, {175, 175}};
4565 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4566 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4567
chaviw9eaa22c2020-07-01 16:21:27 -07004568 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004569
chaviw9eaa22c2020-07-01 16:21:27 -07004570 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004571 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004572 expectedPoints.pop_back();
4573
4574 // Touch Window 2
4575 mWindow2->setWindowTransform(0, -1, 1, 0);
4576 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004577 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004578
4579 // Move both windows
4580 touchedPoints = {{20, 20}, {175, 175}};
4581 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4582 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4583
4584 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004585}
4586
4587TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4588 mWindow1->setWindowScale(0.5f, 0.5f);
4589
4590 // Touch Window 1
4591 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4592 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004593 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004594
4595 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004596 touchedPoints.push_back(PointF{150, 150});
4597 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004598
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004599 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004600
4601 // Move both windows
4602 touchedPoints = {{20, 20}, {175, 175}};
4603 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4604 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4605
chaviw9eaa22c2020-07-01 16:21:27 -07004606 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004607}
4608
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4610 virtual void SetUp() override {
4611 InputDispatcherTest::SetUp();
4612
Chris Yea209fde2020-07-22 13:54:51 -07004613 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004614 mApplication->setDispatchingTimeout(20ms);
4615 mWindow =
4616 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4617 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004618 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004619 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004620
4621 // Set focused application.
4622 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4623
4624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004625 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004626 mWindow->consumeFocusEvent(true);
4627 }
4628
4629 virtual void TearDown() override {
4630 InputDispatcherTest::TearDown();
4631 mWindow.clear();
4632 }
4633
4634protected:
Chris Yea209fde2020-07-22 13:54:51 -07004635 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004636 sp<FakeWindowHandle> mWindow;
4637 static constexpr PointF WINDOW_LOCATION = {20, 20};
4638
4639 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004641 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4642 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004644 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4645 WINDOW_LOCATION));
4646 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004647
4648 sp<FakeWindowHandle> addSpyWindow() {
4649 sp<FakeWindowHandle> spy =
4650 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4651 spy->setTrustedOverlay(true);
4652 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004653 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004654 spy->setDispatchingTimeout(30ms);
4655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4656 return spy;
4657 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004658};
4659
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660// Send a tap and respond, which should not cause an ANR.
4661TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4662 tapOnWindow();
4663 mWindow->consumeMotionDown();
4664 mWindow->consumeMotionUp();
4665 ASSERT_TRUE(mDispatcher->waitForIdle());
4666 mFakePolicy->assertNotifyAnrWasNotCalled();
4667}
4668
4669// Send a regular key and respond, which should not cause an ANR.
4670TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4673 ASSERT_TRUE(mDispatcher->waitForIdle());
4674 mFakePolicy->assertNotifyAnrWasNotCalled();
4675}
4676
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004677TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4678 mWindow->setFocusable(false);
4679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4680 mWindow->consumeFocusEvent(false);
4681
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004682 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004683 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004684 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4685 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004687 // Key will not go to window because we have no focused window.
4688 // The 'no focused window' ANR timer should start instead.
4689
4690 // Now, the focused application goes away.
4691 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4692 // The key should get dropped and there should be no ANR.
4693
4694 ASSERT_TRUE(mDispatcher->waitForIdle());
4695 mFakePolicy->assertNotifyAnrWasNotCalled();
4696}
4697
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004698// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004699// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4700// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004701TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004703 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4704 WINDOW_LOCATION));
4705
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004706 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4707 ASSERT_TRUE(sequenceNum);
4708 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004709 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004711 mWindow->finishEvent(*sequenceNum);
4712 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4713 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004714 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004715 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004716}
4717
4718// Send a key to the app and have the app not respond right away.
4719TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4720 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004722 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4723 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004724 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004725 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004726 ASSERT_TRUE(mDispatcher->waitForIdle());
4727}
4728
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729// We have a focused application, but no focused window
4730TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004731 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4733 mWindow->consumeFocusEvent(false);
4734
4735 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4738 WINDOW_LOCATION));
4739 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4740 mDispatcher->waitForIdle();
4741 mFakePolicy->assertNotifyAnrWasNotCalled();
4742
4743 // Once a focused event arrives, we get an ANR for this application
4744 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4745 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004746 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004748 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004749 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004750 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004751 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752 ASSERT_TRUE(mDispatcher->waitForIdle());
4753}
4754
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004755/**
4756 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4757 * there will not be an ANR.
4758 */
4759TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4760 mWindow->setFocusable(false);
4761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4762 mWindow->consumeFocusEvent(false);
4763
4764 KeyEvent event;
4765 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4766 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4767
4768 // Define a valid key down event that is stale (too old).
4769 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4770 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4771 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4772
4773 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4774
4775 InputEventInjectionResult result =
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004776 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004777 InputEventInjectionSync::WAIT_FOR_RESULT,
4778 INJECT_EVENT_TIMEOUT, policyFlags);
4779 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4780 << "Injection should fail because the event is stale";
4781
4782 ASSERT_TRUE(mDispatcher->waitForIdle());
4783 mFakePolicy->assertNotifyAnrWasNotCalled();
4784 mWindow->assertNoEvents();
4785}
4786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004787// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004788// Make sure that we don't notify policy twice about the same ANR.
4789TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004790 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4792 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793
4794 // Once a focused event arrives, we get an ANR for this application
4795 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4796 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004797 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004799 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801 const std::chrono::duration appTimeout =
4802 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004803 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004805 std::this_thread::sleep_for(appTimeout);
4806 // ANR should not be raised again. It is up to policy to do that if it desires.
4807 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004809 // If we now get a focused window, the ANR should stop, but the policy handles that via
4810 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 ASSERT_TRUE(mDispatcher->waitForIdle());
4812}
4813
4814// We have a focused application, but no focused window
4815TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004816 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4818 mWindow->consumeFocusEvent(false);
4819
4820 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4824 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004825
4826 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004827 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828
4829 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004830 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004831 ASSERT_TRUE(mDispatcher->waitForIdle());
4832 mWindow->assertNoEvents();
4833}
4834
4835/**
4836 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4837 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4838 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4839 * the ANR mechanism should still work.
4840 *
4841 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4842 * DOWN event, while not responding on the second one.
4843 */
4844TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4845 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4846 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4847 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4848 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4849 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004850 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004851
4852 // Now send ACTION_UP, with identical timestamp
4853 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4854 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4855 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4856 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858
4859 // We have now sent down and up. Let's consume first event and then ANR on the second.
4860 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4861 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004862 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863}
4864
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004865// A spy window can receive an ANR
4866TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4867 sp<FakeWindowHandle> spy = addSpyWindow();
4868
4869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4870 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4871 WINDOW_LOCATION));
4872 mWindow->consumeMotionDown();
4873
4874 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4875 ASSERT_TRUE(sequenceNum);
4876 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004877 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004878
4879 spy->finishEvent(*sequenceNum);
4880 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4881 0 /*flags*/);
4882 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004883 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004884}
4885
4886// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004888TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4889 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4892 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004893 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895
4896 // Stuck on the ACTION_UP
4897 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004898 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004900 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004901 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004902 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4903 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904
4905 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4906 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004907 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004908 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004909 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004910}
4911
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004912// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004914TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4915 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916
4917 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004918 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4919 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 mWindow->consumeMotionDown();
4922 // Stuck on the ACTION_UP
4923 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004924 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004926 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004927 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004928 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4929 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930
4931 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4932 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004933 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004935 spy->assertNoEvents();
4936}
4937
4938TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4939 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4940
4941 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4942
4943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4944 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4945 WINDOW_LOCATION));
4946
4947 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4948 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4949 ASSERT_TRUE(consumeSeq);
4950
Prabir Pradhanedd96402022-02-15 01:46:16 -08004951 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004952
4953 monitor.finishEvent(*consumeSeq);
4954 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4955
4956 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004957 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958}
4959
4960// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4961// process events, you don't get an anr. When the window later becomes unresponsive again, you
4962// get an ANR again.
4963// 1. tap -> block on ACTION_UP -> receive ANR
4964// 2. consume all pending events (= queue becomes healthy again)
4965// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4966TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4967 tapOnWindow();
4968
4969 mWindow->consumeMotionDown();
4970 // Block on ACTION_UP
4971 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004972 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004973 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4974 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004975 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976 mWindow->assertNoEvents();
4977
4978 tapOnWindow();
4979 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004980 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 mWindow->consumeMotionUp();
4982
4983 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004984 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004985 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986 mWindow->assertNoEvents();
4987}
4988
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004989// If a connection remains unresponsive for a while, make sure policy is only notified once about
4990// it.
4991TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004993 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4994 WINDOW_LOCATION));
4995
4996 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004997 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004998 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004999 // 'notifyConnectionUnresponsive' should only be called once per connection
5000 mFakePolicy->assertNotifyAnrWasNotCalled();
5001 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002 mWindow->consumeMotionDown();
5003 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5004 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5005 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005006 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005007 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005008 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005009}
5010
5011/**
5012 * If a window is processing a motion event, and then a key event comes in, the key event should
5013 * not to to the focused window until the motion is processed.
5014 *
5015 * Warning!!!
5016 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5017 * and the injection timeout that we specify when injecting the key.
5018 * We must have the injection timeout (10ms) be smaller than
5019 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5020 *
5021 * If that value changes, this test should also change.
5022 */
5023TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5024 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5026
5027 tapOnWindow();
5028 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5029 ASSERT_TRUE(downSequenceNum);
5030 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5031 ASSERT_TRUE(upSequenceNum);
5032 // Don't finish the events yet, and send a key
5033 // Injection will "succeed" because we will eventually give up and send the key to the focused
5034 // window even if motions are still being processed. But because the injection timeout is short,
5035 // we will receive INJECTION_TIMED_OUT as the result.
5036
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005037 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005038 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005039 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5040 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005041 // Key will not be sent to the window, yet, because the window is still processing events
5042 // and the key remains pending, waiting for the touch events to be processed
5043 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5044 ASSERT_FALSE(keySequenceNum);
5045
5046 std::this_thread::sleep_for(500ms);
5047 // if we wait long enough though, dispatcher will give up, and still send the key
5048 // to the focused window, even though we have not yet finished the motion event
5049 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5050 mWindow->finishEvent(*downSequenceNum);
5051 mWindow->finishEvent(*upSequenceNum);
5052}
5053
5054/**
5055 * If a window is processing a motion event, and then a key event comes in, the key event should
5056 * not go to the focused window until the motion is processed.
5057 * If then a new motion comes in, then the pending key event should be going to the currently
5058 * focused window right away.
5059 */
5060TEST_F(InputDispatcherSingleWindowAnr,
5061 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5062 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5064
5065 tapOnWindow();
5066 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5067 ASSERT_TRUE(downSequenceNum);
5068 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5069 ASSERT_TRUE(upSequenceNum);
5070 // Don't finish the events yet, and send a key
5071 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005073 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005074 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005075 // At this point, key is still pending, and should not be sent to the application yet.
5076 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5077 ASSERT_FALSE(keySequenceNum);
5078
5079 // Now tap down again. It should cause the pending key to go to the focused window right away.
5080 tapOnWindow();
5081 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5082 // the other events yet. We can finish events in any order.
5083 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5084 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5085 mWindow->consumeMotionDown();
5086 mWindow->consumeMotionUp();
5087 mWindow->assertNoEvents();
5088}
5089
5090class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5091 virtual void SetUp() override {
5092 InputDispatcherTest::SetUp();
5093
Chris Yea209fde2020-07-22 13:54:51 -07005094 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005095 mApplication->setDispatchingTimeout(10ms);
5096 mUnfocusedWindow =
5097 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5098 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005100 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005101
5102 mFocusedWindow =
5103 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005104 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005105 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005106
5107 // Set focused application.
5108 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005109 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110
5111 // Expect one focus window exist in display.
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005113 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005114 mFocusedWindow->consumeFocusEvent(true);
5115 }
5116
5117 virtual void TearDown() override {
5118 InputDispatcherTest::TearDown();
5119
5120 mUnfocusedWindow.clear();
5121 mFocusedWindow.clear();
5122 }
5123
5124protected:
Chris Yea209fde2020-07-22 13:54:51 -07005125 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005126 sp<FakeWindowHandle> mUnfocusedWindow;
5127 sp<FakeWindowHandle> mFocusedWindow;
5128 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5129 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5130 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5131
5132 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5133
5134 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5135
5136private:
5137 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005139 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5140 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005142 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5143 location));
5144 }
5145};
5146
5147// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5148// should be ANR'd first.
5149TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005151 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5152 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005153 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005154 mFocusedWindow->consumeMotionDown();
5155 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5156 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5157 // We consumed all events, so no ANR
5158 ASSERT_TRUE(mDispatcher->waitForIdle());
5159 mFakePolicy->assertNotifyAnrWasNotCalled();
5160
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005161 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005162 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5163 FOCUSED_WINDOW_LOCATION));
5164 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5165 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005166
5167 const std::chrono::duration timeout =
5168 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005169 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005170 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5171 // sequence to make it consistent
5172 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005173 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005174 mFocusedWindow->consumeMotionDown();
5175 // This cancel is generated because the connection was unresponsive
5176 mFocusedWindow->consumeMotionCancel();
5177 mFocusedWindow->assertNoEvents();
5178 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005179 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005180 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5181 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005182 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005183}
5184
5185// If we have 2 windows with identical timeouts that are both unresponsive,
5186// it doesn't matter which order they should have ANR.
5187// But we should receive ANR for both.
5188TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5189 // Set the timeout for unfocused window to match the focused window
5190 mUnfocusedWindow->setDispatchingTimeout(10ms);
5191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5192
5193 tapOnFocusedWindow();
5194 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005195 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5196 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5197 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005198
5199 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005200 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5201 mFocusedWindow->getToken() == anrConnectionToken2);
5202 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5203 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005204
5205 ASSERT_TRUE(mDispatcher->waitForIdle());
5206 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005207
5208 mFocusedWindow->consumeMotionDown();
5209 mFocusedWindow->consumeMotionUp();
5210 mUnfocusedWindow->consumeMotionOutside();
5211
Prabir Pradhanedd96402022-02-15 01:46:16 -08005212 sp<IBinder> responsiveToken1, responsiveToken2;
5213 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5214 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005215
5216 // Both applications should be marked as responsive, in any order
5217 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5218 mFocusedWindow->getToken() == responsiveToken2);
5219 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5220 mUnfocusedWindow->getToken() == responsiveToken2);
5221 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222}
5223
5224// If a window is already not responding, the second tap on the same window should be ignored.
5225// We should also log an error to account for the dropped event (not tested here).
5226// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5227TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5228 tapOnFocusedWindow();
5229 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5230 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5231 // Receive the events, but don't respond
5232 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5233 ASSERT_TRUE(downEventSequenceNum);
5234 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5235 ASSERT_TRUE(upEventSequenceNum);
5236 const std::chrono::duration timeout =
5237 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005238 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005239
5240 // Tap once again
5241 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005242 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005243 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5244 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005245 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005246 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5247 FOCUSED_WINDOW_LOCATION));
5248 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5249 // valid touch target
5250 mUnfocusedWindow->assertNoEvents();
5251
5252 // Consume the first tap
5253 mFocusedWindow->finishEvent(*downEventSequenceNum);
5254 mFocusedWindow->finishEvent(*upEventSequenceNum);
5255 ASSERT_TRUE(mDispatcher->waitForIdle());
5256 // The second tap did not go to the focused window
5257 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005258 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005259 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5260 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005261 mFakePolicy->assertNotifyAnrWasNotCalled();
5262}
5263
5264// If you tap outside of all windows, there will not be ANR
5265TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005266 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005267 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5268 LOCATION_OUTSIDE_ALL_WINDOWS));
5269 ASSERT_TRUE(mDispatcher->waitForIdle());
5270 mFakePolicy->assertNotifyAnrWasNotCalled();
5271}
5272
5273// Since the focused window is paused, tapping on it should not produce any events
5274TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5275 mFocusedWindow->setPaused(true);
5276 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5277
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005278 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005279 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5280 FOCUSED_WINDOW_LOCATION));
5281
5282 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5283 ASSERT_TRUE(mDispatcher->waitForIdle());
5284 // Should not ANR because the window is paused, and touches shouldn't go to it
5285 mFakePolicy->assertNotifyAnrWasNotCalled();
5286
5287 mFocusedWindow->assertNoEvents();
5288 mUnfocusedWindow->assertNoEvents();
5289}
5290
5291/**
5292 * If a window is processing a motion event, and then a key event comes in, the key event should
5293 * not to to the focused window until the motion is processed.
5294 * If a different window becomes focused at this time, the key should go to that window instead.
5295 *
5296 * Warning!!!
5297 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5298 * and the injection timeout that we specify when injecting the key.
5299 * We must have the injection timeout (10ms) be smaller than
5300 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5301 *
5302 * If that value changes, this test should also change.
5303 */
5304TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5305 // Set a long ANR timeout to prevent it from triggering
5306 mFocusedWindow->setDispatchingTimeout(2s);
5307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5308
5309 tapOnUnfocusedWindow();
5310 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5311 ASSERT_TRUE(downSequenceNum);
5312 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5313 ASSERT_TRUE(upSequenceNum);
5314 // Don't finish the events yet, and send a key
5315 // Injection will succeed because we will eventually give up and send the key to the focused
5316 // window even if motions are still being processed.
5317
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005318 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005319 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005320 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5321 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005322 // Key will not be sent to the window, yet, because the window is still processing events
5323 // and the key remains pending, waiting for the touch events to be processed
5324 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5325 ASSERT_FALSE(keySequenceNum);
5326
5327 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005328 mFocusedWindow->setFocusable(false);
5329 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005331 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005332
5333 // Focus events should precede the key events
5334 mUnfocusedWindow->consumeFocusEvent(true);
5335 mFocusedWindow->consumeFocusEvent(false);
5336
5337 // Finish the tap events, which should unblock dispatcher
5338 mUnfocusedWindow->finishEvent(*downSequenceNum);
5339 mUnfocusedWindow->finishEvent(*upSequenceNum);
5340
5341 // Now that all queues are cleared and no backlog in the connections, the key event
5342 // can finally go to the newly focused "mUnfocusedWindow".
5343 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5344 mFocusedWindow->assertNoEvents();
5345 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005346 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005347}
5348
5349// When the touch stream is split across 2 windows, and one of them does not respond,
5350// then ANR should be raised and the touch should be canceled for the unresponsive window.
5351// The other window should not be affected by that.
5352TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5353 // Touch Window 1
5354 NotifyMotionArgs motionArgs =
5355 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5356 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5357 mDispatcher->notifyMotion(&motionArgs);
5358 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5359 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5360
5361 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005362 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5363 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005364 mDispatcher->notifyMotion(&motionArgs);
5365
5366 const std::chrono::duration timeout =
5367 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005368 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005369
5370 mUnfocusedWindow->consumeMotionDown();
5371 mFocusedWindow->consumeMotionDown();
5372 // Focused window may or may not receive ACTION_MOVE
5373 // But it should definitely receive ACTION_CANCEL due to the ANR
5374 InputEvent* event;
5375 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5376 ASSERT_TRUE(moveOrCancelSequenceNum);
5377 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5378 ASSERT_NE(nullptr, event);
5379 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5380 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5381 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5382 mFocusedWindow->consumeMotionCancel();
5383 } else {
5384 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5385 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005386 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005387 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5388 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005389
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005390 mUnfocusedWindow->assertNoEvents();
5391 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005392 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005393}
5394
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005395/**
5396 * If we have no focused window, and a key comes in, we start the ANR timer.
5397 * The focused application should add a focused window before the timer runs out to prevent ANR.
5398 *
5399 * If the user touches another application during this time, the key should be dropped.
5400 * Next, if a new focused window comes in, without toggling the focused application,
5401 * then no ANR should occur.
5402 *
5403 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5404 * but in some cases the policy may not update the focused application.
5405 */
5406TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5407 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5408 std::make_shared<FakeApplicationHandle>();
5409 focusedApplication->setDispatchingTimeout(60ms);
5410 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5411 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5412 mFocusedWindow->setFocusable(false);
5413
5414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5415 mFocusedWindow->consumeFocusEvent(false);
5416
5417 // Send a key. The ANR timer should start because there is no focused window.
5418 // 'focusedApplication' will get blamed if this timer completes.
5419 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005420 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005421 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005422 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5423 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005425
5426 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5427 // then the injected touches won't cause the focused event to get dropped.
5428 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5429 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5430 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5431 // For this test, it means that the key would get delivered to the window once it becomes
5432 // focused.
5433 std::this_thread::sleep_for(10ms);
5434
5435 // Touch unfocused window. This should force the pending key to get dropped.
5436 NotifyMotionArgs motionArgs =
5437 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5438 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5439 mDispatcher->notifyMotion(&motionArgs);
5440
5441 // We do not consume the motion right away, because that would require dispatcher to first
5442 // process (== drop) the key event, and by that time, ANR will be raised.
5443 // Set the focused window first.
5444 mFocusedWindow->setFocusable(true);
5445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5446 setFocusedWindow(mFocusedWindow);
5447 mFocusedWindow->consumeFocusEvent(true);
5448 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5449 // to another application. This could be a bug / behaviour in the policy.
5450
5451 mUnfocusedWindow->consumeMotionDown();
5452
5453 ASSERT_TRUE(mDispatcher->waitForIdle());
5454 // Should not ANR because we actually have a focused window. It was just added too slowly.
5455 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5456}
5457
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005458// These tests ensure we cannot send touch events to a window that's positioned behind a window
5459// that has feature NO_INPUT_CHANNEL.
5460// Layout:
5461// Top (closest to user)
5462// mNoInputWindow (above all windows)
5463// mBottomWindow
5464// Bottom (furthest from user)
5465class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5466 virtual void SetUp() override {
5467 InputDispatcherTest::SetUp();
5468
5469 mApplication = std::make_shared<FakeApplicationHandle>();
5470 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5471 "Window without input channel", ADISPLAY_ID_DEFAULT,
5472 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5473
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005474 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005475 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5476 // It's perfectly valid for this window to not have an associated input channel
5477
5478 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5479 ADISPLAY_ID_DEFAULT);
5480 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5481
5482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5483 }
5484
5485protected:
5486 std::shared_ptr<FakeApplicationHandle> mApplication;
5487 sp<FakeWindowHandle> mNoInputWindow;
5488 sp<FakeWindowHandle> mBottomWindow;
5489};
5490
5491TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5492 PointF touchedPoint = {10, 10};
5493
5494 NotifyMotionArgs motionArgs =
5495 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5496 ADISPLAY_ID_DEFAULT, {touchedPoint});
5497 mDispatcher->notifyMotion(&motionArgs);
5498
5499 mNoInputWindow->assertNoEvents();
5500 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5501 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5502 // and therefore should prevent mBottomWindow from receiving touches
5503 mBottomWindow->assertNoEvents();
5504}
5505
5506/**
5507 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5508 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5509 */
5510TEST_F(InputDispatcherMultiWindowOcclusionTests,
5511 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5512 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5513 "Window with input channel and NO_INPUT_CHANNEL",
5514 ADISPLAY_ID_DEFAULT);
5515
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005516 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005517 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5519
5520 PointF touchedPoint = {10, 10};
5521
5522 NotifyMotionArgs motionArgs =
5523 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5524 ADISPLAY_ID_DEFAULT, {touchedPoint});
5525 mDispatcher->notifyMotion(&motionArgs);
5526
5527 mNoInputWindow->assertNoEvents();
5528 mBottomWindow->assertNoEvents();
5529}
5530
Vishnu Nair958da932020-08-21 17:12:37 -07005531class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5532protected:
5533 std::shared_ptr<FakeApplicationHandle> mApp;
5534 sp<FakeWindowHandle> mWindow;
5535 sp<FakeWindowHandle> mMirror;
5536
5537 virtual void SetUp() override {
5538 InputDispatcherTest::SetUp();
5539 mApp = std::make_shared<FakeApplicationHandle>();
5540 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5541 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5542 mWindow->getToken());
5543 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5544 mWindow->setFocusable(true);
5545 mMirror->setFocusable(true);
5546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5547 }
5548};
5549
5550TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5551 // Request focus on a mirrored window
5552 setFocusedWindow(mMirror);
5553
5554 // window gets focused
5555 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5557 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005558 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5559}
5560
5561// A focused & mirrored window remains focused only if the window and its mirror are both
5562// focusable.
5563TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5564 setFocusedWindow(mMirror);
5565
5566 // window gets focused
5567 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5569 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005570 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5572 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005573 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5574
5575 mMirror->setFocusable(false);
5576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5577
5578 // window loses focus since one of the windows associated with the token in not focusable
5579 mWindow->consumeFocusEvent(false);
5580
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005581 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5582 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005583 mWindow->assertNoEvents();
5584}
5585
5586// A focused & mirrored window remains focused until the window and its mirror both become
5587// invisible.
5588TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5589 setFocusedWindow(mMirror);
5590
5591 // window gets focused
5592 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5594 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005595 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5597 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005598 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5599
5600 mMirror->setVisible(false);
5601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5602
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5604 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005605 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5607 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005608 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5609
5610 mWindow->setVisible(false);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5612
5613 // window loses focus only after all windows associated with the token become invisible.
5614 mWindow->consumeFocusEvent(false);
5615
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005616 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5617 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005618 mWindow->assertNoEvents();
5619}
5620
5621// A focused & mirrored window remains focused until both windows are removed.
5622TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5623 setFocusedWindow(mMirror);
5624
5625 // window gets focused
5626 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5628 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005629 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5631 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005632 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5633
5634 // single window is removed but the window token remains focused
5635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5636
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5638 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005639 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5641 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005642 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5643
5644 // Both windows are removed
5645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5646 mWindow->consumeFocusEvent(false);
5647
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005648 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5649 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005650 mWindow->assertNoEvents();
5651}
5652
5653// Focus request can be pending until one window becomes visible.
5654TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5655 // Request focus on an invisible mirror.
5656 mWindow->setVisible(false);
5657 mMirror->setVisible(false);
5658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5659 setFocusedWindow(mMirror);
5660
5661 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005663 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005664 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005665
5666 mMirror->setVisible(true);
5667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5668
5669 // window gets focused
5670 mWindow->consumeFocusEvent(true);
5671 // window gets the pending key event
5672 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5673}
Prabir Pradhan99987712020-11-10 18:43:05 -08005674
5675class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5676protected:
5677 std::shared_ptr<FakeApplicationHandle> mApp;
5678 sp<FakeWindowHandle> mWindow;
5679 sp<FakeWindowHandle> mSecondWindow;
5680
5681 void SetUp() override {
5682 InputDispatcherTest::SetUp();
5683 mApp = std::make_shared<FakeApplicationHandle>();
5684 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5685 mWindow->setFocusable(true);
5686 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5687 mSecondWindow->setFocusable(true);
5688
5689 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5691
5692 setFocusedWindow(mWindow);
5693 mWindow->consumeFocusEvent(true);
5694 }
5695
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005696 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5697 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005698 mDispatcher->notifyPointerCaptureChanged(&args);
5699 }
5700
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005701 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5702 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005703 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005704 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5705 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005706 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005707 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005708 }
5709};
5710
5711TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5712 // Ensure that capture cannot be obtained for unfocused windows.
5713 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5714 mFakePolicy->assertSetPointerCaptureNotCalled();
5715 mSecondWindow->assertNoEvents();
5716
5717 // Ensure that capture can be enabled from the focus window.
5718 requestAndVerifyPointerCapture(mWindow, true);
5719
5720 // Ensure that capture cannot be disabled from a window that does not have capture.
5721 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5722 mFakePolicy->assertSetPointerCaptureNotCalled();
5723
5724 // Ensure that capture can be disabled from the window with capture.
5725 requestAndVerifyPointerCapture(mWindow, false);
5726}
5727
5728TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005729 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005730
5731 setFocusedWindow(mSecondWindow);
5732
5733 // Ensure that the capture disabled event was sent first.
5734 mWindow->consumeCaptureEvent(false);
5735 mWindow->consumeFocusEvent(false);
5736 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005737 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005738
5739 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005740 notifyPointerCaptureChanged({});
5741 notifyPointerCaptureChanged(request);
5742 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005743 mWindow->assertNoEvents();
5744 mSecondWindow->assertNoEvents();
5745 mFakePolicy->assertSetPointerCaptureNotCalled();
5746}
5747
5748TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005749 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005750
5751 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005752 notifyPointerCaptureChanged({});
5753 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005754
5755 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005756 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005757 mWindow->consumeCaptureEvent(false);
5758 mWindow->assertNoEvents();
5759}
5760
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005761TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5762 requestAndVerifyPointerCapture(mWindow, true);
5763
5764 // The first window loses focus.
5765 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005766 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005767 mWindow->consumeCaptureEvent(false);
5768
5769 // Request Pointer Capture from the second window before the notification from InputReader
5770 // arrives.
5771 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005772 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005773
5774 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005775 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005776
5777 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005778 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005779
5780 mSecondWindow->consumeFocusEvent(true);
5781 mSecondWindow->consumeCaptureEvent(true);
5782}
5783
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005784TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5785 // App repeatedly enables and disables capture.
5786 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5787 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5788 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5789 mFakePolicy->assertSetPointerCaptureCalled(false);
5790 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5791 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5792
5793 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5794 // first request is now stale, this should do nothing.
5795 notifyPointerCaptureChanged(firstRequest);
5796 mWindow->assertNoEvents();
5797
5798 // InputReader notifies that the second request was enabled.
5799 notifyPointerCaptureChanged(secondRequest);
5800 mWindow->consumeCaptureEvent(true);
5801}
5802
Prabir Pradhan7092e262022-05-03 16:51:09 +00005803TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5804 requestAndVerifyPointerCapture(mWindow, true);
5805
5806 // App toggles pointer capture off and on.
5807 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5808 mFakePolicy->assertSetPointerCaptureCalled(false);
5809
5810 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5811 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5812
5813 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5814 // preceding "disable" request.
5815 notifyPointerCaptureChanged(enableRequest);
5816
5817 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5818 // any notifications.
5819 mWindow->assertNoEvents();
5820}
5821
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005822class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5823protected:
5824 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005825
5826 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5827 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5828
5829 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5830 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5831
5832 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5833 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5834 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5835 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5836 MAXIMUM_OBSCURING_OPACITY);
5837
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005838 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005839 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005840 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005841
5842 sp<FakeWindowHandle> mTouchWindow;
5843
5844 virtual void SetUp() override {
5845 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005846 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005847 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5848 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5849 }
5850
5851 virtual void TearDown() override {
5852 InputDispatcherTest::TearDown();
5853 mTouchWindow.clear();
5854 }
5855
chaviw3277faf2021-05-19 16:45:23 -05005856 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5857 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005858 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005859 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005860 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005861 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005862 return window;
5863 }
5864
5865 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5866 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5867 sp<FakeWindowHandle> window =
5868 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5869 // Generate an arbitrary PID based on the UID
5870 window->setOwnerInfo(1777 + (uid % 10000), uid);
5871 return window;
5872 }
5873
5874 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5875 NotifyMotionArgs args =
5876 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5877 ADISPLAY_ID_DEFAULT, points);
5878 mDispatcher->notifyMotion(&args);
5879 }
5880};
5881
5882TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005883 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005884 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005886
5887 touch();
5888
5889 mTouchWindow->assertNoEvents();
5890}
5891
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005892TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005893 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5894 const sp<FakeWindowHandle>& w =
5895 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5897
5898 touch();
5899
5900 mTouchWindow->assertNoEvents();
5901}
5902
5903TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005904 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5905 const sp<FakeWindowHandle>& w =
5906 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5908
5909 touch();
5910
5911 w->assertNoEvents();
5912}
5913
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005914TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005915 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005917
5918 touch();
5919
5920 mTouchWindow->consumeAnyMotionDown();
5921}
5922
5923TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005924 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005925 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005926 w->setFrame(Rect(0, 0, 50, 50));
5927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005928
5929 touch({PointF{100, 100}});
5930
5931 mTouchWindow->consumeAnyMotionDown();
5932}
5933
5934TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005935 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005936 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5938
5939 touch();
5940
5941 mTouchWindow->consumeAnyMotionDown();
5942}
5943
5944TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5945 const sp<FakeWindowHandle>& w =
5946 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005948
5949 touch();
5950
5951 mTouchWindow->consumeAnyMotionDown();
5952}
5953
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005954TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5955 const sp<FakeWindowHandle>& w =
5956 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5958
5959 touch();
5960
5961 w->assertNoEvents();
5962}
5963
5964/**
5965 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5966 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5967 * window, the occluding window will still receive ACTION_OUTSIDE event.
5968 */
5969TEST_F(InputDispatcherUntrustedTouchesTest,
5970 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5971 const sp<FakeWindowHandle>& w =
5972 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005973 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5975
5976 touch();
5977
5978 w->consumeMotionOutside();
5979}
5980
5981TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5982 const sp<FakeWindowHandle>& w =
5983 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005984 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5986
5987 touch();
5988
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005989 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005990}
5991
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005992TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005993 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005994 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5995 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5997
5998 touch();
5999
6000 mTouchWindow->consumeAnyMotionDown();
6001}
6002
6003TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6004 const sp<FakeWindowHandle>& w =
6005 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6006 MAXIMUM_OBSCURING_OPACITY);
6007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006008
6009 touch();
6010
6011 mTouchWindow->consumeAnyMotionDown();
6012}
6013
6014TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006015 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006016 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6017 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6019
6020 touch();
6021
6022 mTouchWindow->assertNoEvents();
6023}
6024
6025TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6026 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6027 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006028 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6029 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006030 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006031 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6032 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6034
6035 touch();
6036
6037 mTouchWindow->assertNoEvents();
6038}
6039
6040TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6041 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6042 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006043 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6044 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006045 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006046 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6047 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6049
6050 touch();
6051
6052 mTouchWindow->consumeAnyMotionDown();
6053}
6054
6055TEST_F(InputDispatcherUntrustedTouchesTest,
6056 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6057 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006058 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6059 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006060 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006061 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6062 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6064
6065 touch();
6066
6067 mTouchWindow->consumeAnyMotionDown();
6068}
6069
6070TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6071 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006072 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6073 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006074 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006075 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6076 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006078
6079 touch();
6080
6081 mTouchWindow->assertNoEvents();
6082}
6083
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006084TEST_F(InputDispatcherUntrustedTouchesTest,
6085 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6086 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006087 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6088 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006089 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006090 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6091 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6093
6094 touch();
6095
6096 mTouchWindow->assertNoEvents();
6097}
6098
6099TEST_F(InputDispatcherUntrustedTouchesTest,
6100 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6101 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006102 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6103 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006104 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006105 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6106 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6108
6109 touch();
6110
6111 mTouchWindow->consumeAnyMotionDown();
6112}
6113
6114TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6115 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006116 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6117 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6119
6120 touch();
6121
6122 mTouchWindow->consumeAnyMotionDown();
6123}
6124
6125TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6126 const sp<FakeWindowHandle>& w =
6127 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6129
6130 touch();
6131
6132 mTouchWindow->consumeAnyMotionDown();
6133}
6134
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006135TEST_F(InputDispatcherUntrustedTouchesTest,
6136 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6137 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6138 const sp<FakeWindowHandle>& w =
6139 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6141
6142 touch();
6143
6144 mTouchWindow->assertNoEvents();
6145}
6146
6147TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6148 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6149 const sp<FakeWindowHandle>& w =
6150 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6152
6153 touch();
6154
6155 mTouchWindow->consumeAnyMotionDown();
6156}
6157
6158TEST_F(InputDispatcherUntrustedTouchesTest,
6159 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6160 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6161 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006162 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6163 OPACITY_ABOVE_THRESHOLD);
6164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6165
6166 touch();
6167
6168 mTouchWindow->consumeAnyMotionDown();
6169}
6170
6171TEST_F(InputDispatcherUntrustedTouchesTest,
6172 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6173 const sp<FakeWindowHandle>& w1 =
6174 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6175 OPACITY_BELOW_THRESHOLD);
6176 const sp<FakeWindowHandle>& w2 =
6177 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6178 OPACITY_BELOW_THRESHOLD);
6179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6180
6181 touch();
6182
6183 mTouchWindow->assertNoEvents();
6184}
6185
6186/**
6187 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6188 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6189 * (which alone would result in allowing touches) does not affect the blocking behavior.
6190 */
6191TEST_F(InputDispatcherUntrustedTouchesTest,
6192 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6193 const sp<FakeWindowHandle>& wB =
6194 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6195 OPACITY_BELOW_THRESHOLD);
6196 const sp<FakeWindowHandle>& wC =
6197 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6198 OPACITY_BELOW_THRESHOLD);
6199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6200
6201 touch();
6202
6203 mTouchWindow->assertNoEvents();
6204}
6205
6206/**
6207 * This test is testing that a window from a different UID but with same application token doesn't
6208 * block the touch. Apps can share the application token for close UI collaboration for example.
6209 */
6210TEST_F(InputDispatcherUntrustedTouchesTest,
6211 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6212 const sp<FakeWindowHandle>& w =
6213 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6214 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6216
6217 touch();
6218
6219 mTouchWindow->consumeAnyMotionDown();
6220}
6221
arthurhungb89ccb02020-12-30 16:19:01 +08006222class InputDispatcherDragTests : public InputDispatcherTest {
6223protected:
6224 std::shared_ptr<FakeApplicationHandle> mApp;
6225 sp<FakeWindowHandle> mWindow;
6226 sp<FakeWindowHandle> mSecondWindow;
6227 sp<FakeWindowHandle> mDragWindow;
6228
6229 void SetUp() override {
6230 InputDispatcherTest::SetUp();
6231 mApp = std::make_shared<FakeApplicationHandle>();
6232 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6233 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006234
6235 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6236 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006237
6238 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6240 }
6241
Arthur Hung54745652022-04-20 07:17:41 +00006242 void injectDown() {
arthurhungb89ccb02020-12-30 16:19:01 +08006243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6244 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6245 {50, 50}))
6246 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6247
6248 // Window should receive motion event.
6249 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006250 }
6251
6252 // Start performing drag, we will create a drag window and transfer touch to it.
6253 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6254 // Returns true on success.
6255 bool performDrag(bool sendDown = true) {
6256 if (sendDown) {
6257 injectDown();
6258 }
arthurhungb89ccb02020-12-30 16:19:01 +08006259
6260 // The drag window covers the entire display
6261 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6262 mDispatcher->setInputWindows(
6263 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6264
6265 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006266 bool transferred =
6267 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6268 true /* isDragDrop */);
6269 if (transferred) {
6270 mWindow->consumeMotionCancel();
6271 mDragWindow->consumeMotionDown();
6272 }
6273 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006274 }
arthurhung6d4bed92021-03-17 11:59:33 +08006275
6276 // Start performing drag, we will create a drag window and transfer touch to it.
6277 void performStylusDrag() {
6278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6279 injectMotionEvent(mDispatcher,
6280 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6281 AINPUT_SOURCE_STYLUS)
6282 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6283 .pointer(PointerBuilder(0,
6284 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6285 .x(50)
6286 .y(50))
6287 .build()));
6288 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6289
6290 // The drag window covers the entire display
6291 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6292 mDispatcher->setInputWindows(
6293 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6294
6295 // Transfer touch focus to the drag window
6296 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6297 true /* isDragDrop */);
6298 mWindow->consumeMotionCancel();
6299 mDragWindow->consumeMotionDown();
6300 }
arthurhungb89ccb02020-12-30 16:19:01 +08006301};
6302
6303TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6304 performDrag();
6305
6306 // Move on window.
6307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6308 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6309 ADISPLAY_ID_DEFAULT, {50, 50}))
6310 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6311 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6312 mWindow->consumeDragEvent(false, 50, 50);
6313 mSecondWindow->assertNoEvents();
6314
6315 // Move to another window.
6316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6317 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6318 ADISPLAY_ID_DEFAULT, {150, 50}))
6319 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6320 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6321 mWindow->consumeDragEvent(true, 150, 50);
6322 mSecondWindow->consumeDragEvent(false, 50, 50);
6323
6324 // Move back to original window.
6325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6326 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6327 ADISPLAY_ID_DEFAULT, {50, 50}))
6328 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6329 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6330 mWindow->consumeDragEvent(false, 50, 50);
6331 mSecondWindow->consumeDragEvent(true, -50, 50);
6332
6333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6334 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6336 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6337 mWindow->assertNoEvents();
6338 mSecondWindow->assertNoEvents();
6339}
6340
arthurhungf452d0b2021-01-06 00:19:52 +08006341TEST_F(InputDispatcherDragTests, DragAndDrop) {
6342 performDrag();
6343
6344 // Move on window.
6345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6346 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6347 ADISPLAY_ID_DEFAULT, {50, 50}))
6348 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6349 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6350 mWindow->consumeDragEvent(false, 50, 50);
6351 mSecondWindow->assertNoEvents();
6352
6353 // Move to another window.
6354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6355 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6356 ADISPLAY_ID_DEFAULT, {150, 50}))
6357 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6358 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6359 mWindow->consumeDragEvent(true, 150, 50);
6360 mSecondWindow->consumeDragEvent(false, 50, 50);
6361
6362 // drop to another window.
6363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6364 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6365 {150, 50}))
6366 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6367 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6368 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6369 mWindow->assertNoEvents();
6370 mSecondWindow->assertNoEvents();
6371}
6372
arthurhung6d4bed92021-03-17 11:59:33 +08006373TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6374 performStylusDrag();
6375
6376 // Move on window and keep button pressed.
6377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6378 injectMotionEvent(mDispatcher,
6379 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6380 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6381 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6382 .x(50)
6383 .y(50))
6384 .build()))
6385 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6386 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6387 mWindow->consumeDragEvent(false, 50, 50);
6388 mSecondWindow->assertNoEvents();
6389
6390 // Move to another window and release button, expect to drop item.
6391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6392 injectMotionEvent(mDispatcher,
6393 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6394 .buttonState(0)
6395 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6396 .x(150)
6397 .y(50))
6398 .build()))
6399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6400 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6401 mWindow->assertNoEvents();
6402 mSecondWindow->assertNoEvents();
6403 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6404
6405 // nothing to the window.
6406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6407 injectMotionEvent(mDispatcher,
6408 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6409 .buttonState(0)
6410 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6411 .x(150)
6412 .y(50))
6413 .build()))
6414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6415 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6416 mWindow->assertNoEvents();
6417 mSecondWindow->assertNoEvents();
6418}
6419
Arthur Hung54745652022-04-20 07:17:41 +00006420TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08006421 performDrag();
6422
6423 // Set second window invisible.
6424 mSecondWindow->setVisible(false);
6425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6426
6427 // Move on window.
6428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6429 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6430 ADISPLAY_ID_DEFAULT, {50, 50}))
6431 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6432 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6433 mWindow->consumeDragEvent(false, 50, 50);
6434 mSecondWindow->assertNoEvents();
6435
6436 // Move to another window.
6437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6438 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6439 ADISPLAY_ID_DEFAULT, {150, 50}))
6440 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6441 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6442 mWindow->consumeDragEvent(true, 150, 50);
6443 mSecondWindow->assertNoEvents();
6444
6445 // drop to another window.
6446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6447 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6448 {150, 50}))
6449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6450 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6451 mFakePolicy->assertDropTargetEquals(nullptr);
6452 mWindow->assertNoEvents();
6453 mSecondWindow->assertNoEvents();
6454}
6455
Arthur Hung54745652022-04-20 07:17:41 +00006456TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
6457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6459 {50, 50}))
6460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6461 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6462
6463 const MotionEvent secondFingerDownEvent =
6464 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6465 .displayId(ADISPLAY_ID_DEFAULT)
6466 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6467 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6468 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6469 .build();
6470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6471 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6472 InputEventInjectionSync::WAIT_FOR_RESULT))
6473 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6474 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6475
6476 // Should not perform drag and drop when window has multi fingers.
6477 ASSERT_FALSE(performDrag(false));
6478}
6479
6480TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6481 // First down on second window.
6482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6483 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6484 {150, 50}))
6485 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6486
6487 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6488
6489 // Second down on first window.
6490 const MotionEvent secondFingerDownEvent =
6491 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6492 .displayId(ADISPLAY_ID_DEFAULT)
6493 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6494 .pointer(
6495 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6496 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6497 .build();
6498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6499 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6500 InputEventInjectionSync::WAIT_FOR_RESULT))
6501 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6502 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6503
6504 // Perform drag and drop from first window.
6505 ASSERT_TRUE(performDrag(false));
6506
6507 // Move on window.
6508 const MotionEvent secondFingerMoveEvent =
6509 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6510 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6511 .pointer(
6512 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6513 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6514 .build();
6515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6516 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6517 InputEventInjectionSync::WAIT_FOR_RESULT));
6518 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6519 mWindow->consumeDragEvent(false, 50, 50);
6520 mSecondWindow->consumeMotionMove();
6521
6522 // Release the drag pointer should perform drop.
6523 const MotionEvent secondFingerUpEvent =
6524 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6525 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6526 .pointer(
6527 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6528 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6529 .build();
6530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6531 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6532 InputEventInjectionSync::WAIT_FOR_RESULT));
6533 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6534 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6535 mWindow->assertNoEvents();
6536 mSecondWindow->consumeMotionMove();
6537}
6538
Arthur Hung3915c1f2022-05-31 07:17:17 +00006539TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
6540 performDrag();
6541
6542 // Update window of second display.
6543 sp<FakeWindowHandle> windowInSecondary =
6544 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6545 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6546
6547 // Let second display has a touch state.
6548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6549 injectMotionEvent(mDispatcher,
6550 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6551 AINPUT_SOURCE_TOUCHSCREEN)
6552 .displayId(SECOND_DISPLAY_ID)
6553 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6554 .x(100)
6555 .y(100))
6556 .build()));
6557 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6558 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6559 // Update window again.
6560 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6561
6562 // Move on window.
6563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6564 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6565 ADISPLAY_ID_DEFAULT, {50, 50}))
6566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6567 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6568 mWindow->consumeDragEvent(false, 50, 50);
6569 mSecondWindow->assertNoEvents();
6570
6571 // Move to another window.
6572 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6573 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6574 ADISPLAY_ID_DEFAULT, {150, 50}))
6575 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6576 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6577 mWindow->consumeDragEvent(true, 150, 50);
6578 mSecondWindow->consumeDragEvent(false, 50, 50);
6579
6580 // drop to another window.
6581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6582 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6583 {150, 50}))
6584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6585 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6586 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6587 mWindow->assertNoEvents();
6588 mSecondWindow->assertNoEvents();
6589}
6590
Vishnu Nair062a8672021-09-03 16:07:44 -07006591class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6592
6593TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6594 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6595 sp<FakeWindowHandle> window =
6596 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006597 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006598 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6599 window->setFocusable(true);
6600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6601 setFocusedWindow(window);
6602 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6603
6604 // With the flag set, window should not get any input
6605 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6606 mDispatcher->notifyKey(&keyArgs);
6607 window->assertNoEvents();
6608
6609 NotifyMotionArgs motionArgs =
6610 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6611 ADISPLAY_ID_DEFAULT);
6612 mDispatcher->notifyMotion(&motionArgs);
6613 window->assertNoEvents();
6614
6615 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006616 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6618
6619 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6620 mDispatcher->notifyKey(&keyArgs);
6621 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6622
6623 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6624 ADISPLAY_ID_DEFAULT);
6625 mDispatcher->notifyMotion(&motionArgs);
6626 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6627 window->assertNoEvents();
6628}
6629
6630TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6631 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6632 std::make_shared<FakeApplicationHandle>();
6633 sp<FakeWindowHandle> obscuringWindow =
6634 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6635 ADISPLAY_ID_DEFAULT);
6636 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6637 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006638 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6640 sp<FakeWindowHandle> window =
6641 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006642 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006643 window->setOwnerInfo(222, 222);
6644 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6645 window->setFocusable(true);
6646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6647 setFocusedWindow(window);
6648 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6649
6650 // With the flag set, window should not get any input
6651 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6652 mDispatcher->notifyKey(&keyArgs);
6653 window->assertNoEvents();
6654
6655 NotifyMotionArgs motionArgs =
6656 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6657 ADISPLAY_ID_DEFAULT);
6658 mDispatcher->notifyMotion(&motionArgs);
6659 window->assertNoEvents();
6660
6661 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006662 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6664
6665 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6666 mDispatcher->notifyKey(&keyArgs);
6667 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6668
6669 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6670 ADISPLAY_ID_DEFAULT);
6671 mDispatcher->notifyMotion(&motionArgs);
6672 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6673 window->assertNoEvents();
6674}
6675
6676TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6677 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6678 std::make_shared<FakeApplicationHandle>();
6679 sp<FakeWindowHandle> obscuringWindow =
6680 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6681 ADISPLAY_ID_DEFAULT);
6682 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6683 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006684 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006685 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6686 sp<FakeWindowHandle> window =
6687 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006688 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006689 window->setOwnerInfo(222, 222);
6690 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6691 window->setFocusable(true);
6692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6693 setFocusedWindow(window);
6694 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6695
6696 // With the flag set, window should not get any input
6697 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6698 mDispatcher->notifyKey(&keyArgs);
6699 window->assertNoEvents();
6700
6701 NotifyMotionArgs motionArgs =
6702 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6703 ADISPLAY_ID_DEFAULT);
6704 mDispatcher->notifyMotion(&motionArgs);
6705 window->assertNoEvents();
6706
6707 // When the window is no longer obscured because it went on top, it should get input
6708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6709
6710 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6711 mDispatcher->notifyKey(&keyArgs);
6712 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6713
6714 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6715 ADISPLAY_ID_DEFAULT);
6716 mDispatcher->notifyMotion(&motionArgs);
6717 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6718 window->assertNoEvents();
6719}
6720
Antonio Kantekf16f2832021-09-28 04:39:20 +00006721class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6722protected:
6723 std::shared_ptr<FakeApplicationHandle> mApp;
6724 sp<FakeWindowHandle> mWindow;
6725 sp<FakeWindowHandle> mSecondWindow;
6726
6727 void SetUp() override {
6728 InputDispatcherTest::SetUp();
6729
6730 mApp = std::make_shared<FakeApplicationHandle>();
6731 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6732 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006733 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006734 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6735 mSecondWindow->setFocusable(true);
6736
6737 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006739 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006740
6741 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00006742 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6743 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006744 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6745 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6746 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006747 }
6748
Antonio Kantekea47acb2021-12-23 12:41:25 -08006749 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006750 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006751 mWindow->consumeTouchModeEvent(inTouchMode);
6752 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6753 }
6754};
6755
Antonio Kantek26defcf2022-02-08 01:12:27 +00006756TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006757 const WindowInfo& windowInfo = *mWindow->getInfo();
6758 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6759 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006760}
6761
Antonio Kantek26defcf2022-02-08 01:12:27 +00006762TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6763 const WindowInfo& windowInfo = *mWindow->getInfo();
6764 int32_t ownerPid = windowInfo.ownerPid;
6765 int32_t ownerUid = windowInfo.ownerUid;
6766 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6767 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6768 ownerUid, /* hasPermission */ false));
6769 mWindow->assertNoEvents();
6770 mSecondWindow->assertNoEvents();
6771}
6772
6773TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6774 const WindowInfo& windowInfo = *mWindow->getInfo();
6775 int32_t ownerPid = windowInfo.ownerPid;
6776 int32_t ownerUid = windowInfo.ownerUid;
6777 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6778 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6779 /* hasPermission */ true);
6780}
6781
Antonio Kantekf16f2832021-09-28 04:39:20 +00006782TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006783 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006784 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6785 windowInfo.ownerPid, windowInfo.ownerUid,
6786 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006787 mWindow->assertNoEvents();
6788 mSecondWindow->assertNoEvents();
6789}
6790
Antonio Kantek48710e42022-03-24 14:19:30 -07006791TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6792 // Interact with the window first.
6793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6794 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6795 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6796
6797 // Then remove focus.
6798 mWindow->setFocusable(false);
6799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6800
6801 // Assert that caller can switch touch mode by owning one of the last interacted window.
6802 const WindowInfo& windowInfo = *mWindow->getInfo();
6803 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6804 windowInfo.ownerPid, windowInfo.ownerUid,
6805 /* hasPermission= */ false));
6806}
6807
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006808class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6809public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006810 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006811 std::shared_ptr<FakeApplicationHandle> application =
6812 std::make_shared<FakeApplicationHandle>();
6813 std::string name = "Fake Spy ";
6814 name += std::to_string(mSpyCount++);
6815 sp<FakeWindowHandle> spy =
6816 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006817 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006818 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006819 return spy;
6820 }
6821
6822 sp<FakeWindowHandle> createForeground() {
6823 std::shared_ptr<FakeApplicationHandle> application =
6824 std::make_shared<FakeApplicationHandle>();
6825 sp<FakeWindowHandle> window =
6826 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006827 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006828 return window;
6829 }
6830
6831private:
6832 int mSpyCount{0};
6833};
6834
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006835using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006836/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006837 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6838 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006839TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6840 ScopedSilentDeath _silentDeath;
6841
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006842 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006843 spy->setTrustedOverlay(false);
6844 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6845 ".* not a trusted overlay");
6846}
6847
6848/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006849 * Input injection into a display with a spy window but no foreground windows should succeed.
6850 */
6851TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006852 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006853 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6854
6855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6856 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6857 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6858 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6859}
6860
6861/**
6862 * Verify the order in which different input windows receive events. The touched foreground window
6863 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6864 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6865 * receive events before ones belows it.
6866 *
6867 * Here, we set up a scenario with four windows in the following Z order from the top:
6868 * spy1, spy2, window, spy3.
6869 * We then inject an event and verify that the foreground "window" receives it first, followed by
6870 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6871 * window.
6872 */
6873TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6874 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006875 auto spy1 = createSpy();
6876 auto spy2 = createSpy();
6877 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6879 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6880 const size_t numChannels = channels.size();
6881
Michael Wright8e9a8562022-02-09 13:44:29 +00006882 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006883 if (!epollFd.ok()) {
6884 FAIL() << "Failed to create epoll fd";
6885 }
6886
6887 for (size_t i = 0; i < numChannels; i++) {
6888 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6889 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6890 FAIL() << "Failed to add fd to epoll";
6891 }
6892 }
6893
6894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6897
6898 std::vector<size_t> eventOrder;
6899 std::vector<struct epoll_event> events(numChannels);
6900 for (;;) {
6901 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6902 (100ms).count());
6903 if (nFds < 0) {
6904 FAIL() << "Failed to call epoll_wait";
6905 }
6906 if (nFds == 0) {
6907 break; // epoll_wait timed out
6908 }
6909 for (int i = 0; i < nFds; i++) {
6910 ASSERT_EQ(EPOLLIN, events[i].events);
6911 eventOrder.push_back(events[i].data.u64);
6912 channels[i]->consumeMotionDown();
6913 }
6914 }
6915
6916 // Verify the order in which the events were received.
6917 EXPECT_EQ(3u, eventOrder.size());
6918 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6919 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6920 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6921}
6922
6923/**
6924 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6925 */
6926TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6927 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006928 auto spy = createSpy();
6929 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6931
6932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6933 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6935 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6936 spy->assertNoEvents();
6937}
6938
6939/**
6940 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6941 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6942 * to the window.
6943 */
6944TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6945 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006946 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006947 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6949
6950 // Inject an event outside the spy window's touchable region.
6951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6954 window->consumeMotionDown();
6955 spy->assertNoEvents();
6956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6957 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6959 window->consumeMotionUp();
6960 spy->assertNoEvents();
6961
6962 // Inject an event inside the spy window's touchable region.
6963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6964 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6965 {5, 10}))
6966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6967 window->consumeMotionDown();
6968 spy->consumeMotionDown();
6969}
6970
6971/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006972 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006973 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006974 */
6975TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6976 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006977 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006978 auto spy = createSpy();
6979 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006980 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006981 spy->setFrame(Rect{0, 0, 20, 20});
6982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6983
6984 // Inject an event outside the spy window's frame and touchable region.
6985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006986 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6987 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6989 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006990 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006991}
6992
6993/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006994 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6995 * any other windows - including other spy windows - will also be cancelled.
6996 */
6997TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6998 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006999 auto spy1 = createSpy();
7000 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7002
7003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7004 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7006 window->consumeMotionDown();
7007 spy1->consumeMotionDown();
7008 spy2->consumeMotionDown();
7009
7010 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007011 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007012 spy2->assertNoEvents();
7013 spy1->consumeMotionCancel();
7014 window->consumeMotionCancel();
7015
7016 // The rest of the gesture should only be sent to the second spy window.
7017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7018 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7019 ADISPLAY_ID_DEFAULT))
7020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7021 spy2->consumeMotionMove();
7022 spy1->assertNoEvents();
7023 window->assertNoEvents();
7024}
7025
7026/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007027 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7028 * in the middle of the gesture.
7029 */
7030TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
7031 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007032 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7034
7035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7036 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7037 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7038 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7039 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7040
7041 window->releaseChannel();
7042
7043 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7044
7045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7046 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7048 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7049}
7050
7051/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007052 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7053 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007054 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007055TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007056 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007057 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007058
7059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7060
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007061 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7063 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7064 {100, 200}))
7065 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007066 spy->consumeMotionDown();
7067 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007068
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007069 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007070 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007071 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007072
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007073 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007074 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007075 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007076 .displayId(ADISPLAY_ID_DEFAULT)
7077 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7078 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7079 .x(100)
7080 .y(200))
7081 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7082 .build();
7083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7084 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7085 InputEventInjectionSync::WAIT_FOR_RESULT))
7086 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7087
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007088 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7089
7090 // Third finger goes down outside all windows, so injection should fail.
7091 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00007092 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08007093 .displayId(ADISPLAY_ID_DEFAULT)
7094 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7095 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7096 .x(100)
7097 .y(200))
7098 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7099 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7100 .build();
7101 ASSERT_EQ(InputEventInjectionResult::FAILED,
7102 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7103 InputEventInjectionSync::WAIT_FOR_RESULT))
7104 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7105
7106 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007107 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007108}
7109
7110/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007111 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7112 * pointers that are down within its bounds.
7113 */
7114TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7115 auto windowLeft = createForeground();
7116 windowLeft->setFrame({0, 0, 100, 200});
7117 auto windowRight = createForeground();
7118 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007119 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007120 spy->setFrame({0, 0, 200, 200});
7121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7122
7123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7124 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7125 {50, 50}))
7126 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7127 windowLeft->consumeMotionDown();
7128 spy->consumeMotionDown();
7129
7130 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007131 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007132 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7133 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7134 .pointer(
7135 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7136 .build();
7137 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7138 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7139 InputEventInjectionSync::WAIT_FOR_RESULT))
7140 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7141 windowRight->consumeMotionDown();
7142 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7143}
7144
7145/**
7146 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7147 * the spy should receive the second pointer with ACTION_DOWN.
7148 */
7149TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7150 auto window = createForeground();
7151 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007152 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007153 spyRight->setFrame({100, 0, 200, 200});
7154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7155
7156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7157 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7158 {50, 50}))
7159 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7160 window->consumeMotionDown();
7161 spyRight->assertNoEvents();
7162
7163 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007164 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007165 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7166 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7167 .pointer(
7168 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7169 .build();
7170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7171 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7172 InputEventInjectionSync::WAIT_FOR_RESULT))
7173 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7174 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7175 spyRight->consumeMotionDown();
7176}
7177
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007178/**
7179 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7180 * windows should be allowed to control split touch.
7181 */
7182TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007183 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007184 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007185 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007186 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007187
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007188 auto window = createForeground();
7189 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007190
7191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7192
7193 // First finger down, no window touched.
7194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7195 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7196 {100, 200}))
7197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7198 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7199 window->assertNoEvents();
7200
7201 // Second finger down on window, the window should receive touch down.
7202 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007203 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007204 .displayId(ADISPLAY_ID_DEFAULT)
7205 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7206 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7207 .x(100)
7208 .y(200))
7209 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7210 .build();
7211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7212 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7213 InputEventInjectionSync::WAIT_FOR_RESULT))
7214 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7215
7216 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7217 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7218}
7219
7220/**
7221 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7222 * do not receive key events.
7223 */
7224TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007225 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007226 spy->setFocusable(false);
7227
7228 auto window = createForeground();
7229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7230 setFocusedWindow(window);
7231 window->consumeFocusEvent(true);
7232
7233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7234 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7235 window->consumeKeyDown(ADISPLAY_ID_NONE);
7236
7237 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7238 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7239 window->consumeKeyUp(ADISPLAY_ID_NONE);
7240
7241 spy->assertNoEvents();
7242}
7243
Prabir Pradhand65552b2021-10-07 11:23:50 -07007244class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7245public:
7246 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7247 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7248 std::make_shared<FakeApplicationHandle>();
7249 sp<FakeWindowHandle> overlay =
7250 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7251 ADISPLAY_ID_DEFAULT);
7252 overlay->setFocusable(false);
7253 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007254 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007255 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007256 overlay->setTrustedOverlay(true);
7257
7258 std::shared_ptr<FakeApplicationHandle> application =
7259 std::make_shared<FakeApplicationHandle>();
7260 sp<FakeWindowHandle> window =
7261 new FakeWindowHandle(application, mDispatcher, "Application window",
7262 ADISPLAY_ID_DEFAULT);
7263 window->setFocusable(true);
7264 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007265
7266 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7268 setFocusedWindow(window);
7269 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7270 return {std::move(overlay), std::move(window)};
7271 }
7272
7273 void sendFingerEvent(int32_t action) {
7274 NotifyMotionArgs motionArgs =
7275 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7276 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7277 mDispatcher->notifyMotion(&motionArgs);
7278 }
7279
7280 void sendStylusEvent(int32_t action) {
7281 NotifyMotionArgs motionArgs =
7282 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7283 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7284 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7285 mDispatcher->notifyMotion(&motionArgs);
7286 }
7287};
7288
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007289using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7290
7291TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7292 ScopedSilentDeath _silentDeath;
7293
Prabir Pradhand65552b2021-10-07 11:23:50 -07007294 auto [overlay, window] = setupStylusOverlayScenario();
7295 overlay->setTrustedOverlay(false);
7296 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7297 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7298 ".* not a trusted overlay");
7299}
7300
7301TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7302 auto [overlay, window] = setupStylusOverlayScenario();
7303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7304
7305 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7306 overlay->consumeMotionDown();
7307 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7308 overlay->consumeMotionUp();
7309
7310 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7311 window->consumeMotionDown();
7312 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7313 window->consumeMotionUp();
7314
7315 overlay->assertNoEvents();
7316 window->assertNoEvents();
7317}
7318
7319TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7320 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007321 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7323
7324 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7325 overlay->consumeMotionDown();
7326 window->consumeMotionDown();
7327 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7328 overlay->consumeMotionUp();
7329 window->consumeMotionUp();
7330
7331 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7332 window->consumeMotionDown();
7333 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7334 window->consumeMotionUp();
7335
7336 overlay->assertNoEvents();
7337 window->assertNoEvents();
7338}
7339
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007340/**
7341 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7342 * The scenario is as follows:
7343 * - The stylus interceptor overlay is configured as a spy window.
7344 * - The stylus interceptor spy receives the start of a new stylus gesture.
7345 * - It pilfers pointers and then configures itself to no longer be a spy.
7346 * - The stylus interceptor continues to receive the rest of the gesture.
7347 */
7348TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7349 auto [overlay, window] = setupStylusOverlayScenario();
7350 overlay->setSpy(true);
7351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7352
7353 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7354 overlay->consumeMotionDown();
7355 window->consumeMotionDown();
7356
7357 // The interceptor pilfers the pointers.
7358 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7359 window->consumeMotionCancel();
7360
7361 // The interceptor configures itself so that it is no longer a spy.
7362 overlay->setSpy(false);
7363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7364
7365 // It continues to receive the rest of the stylus gesture.
7366 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7367 overlay->consumeMotionMove();
7368 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7369 overlay->consumeMotionUp();
7370
7371 window->assertNoEvents();
7372}
7373
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00007374struct User {
7375 int32_t mPid;
7376 int32_t mUid;
7377 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7378 std::unique_ptr<InputDispatcher>& mDispatcher;
7379
7380 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7381 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7382
7383 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7384 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7385 ADISPLAY_ID_DEFAULT, {100, 200},
7386 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7387 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7388 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7389 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7390 }
7391
7392 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7393 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7394 InputEventInjectionSync::WAIT_FOR_RESULT,
7395 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7396 mPolicyFlags);
7397 }
7398
7399 sp<FakeWindowHandle> createWindow() const {
7400 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7401 std::make_shared<FakeApplicationHandle>();
7402 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7403 "Owned Window", ADISPLAY_ID_DEFAULT);
7404 window->setOwnerInfo(mPid, mUid);
7405 return window;
7406 }
7407};
7408
7409using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7410
7411TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7412 auto owner = User(mDispatcher, 10, 11);
7413 auto window = owner.createWindow();
7414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7415
7416 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7417 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7418 window->consumeMotionDown();
7419
7420 setFocusedWindow(window);
7421 window->consumeFocusEvent(true);
7422
7423 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7424 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7425 window->consumeKeyDown(ADISPLAY_ID_NONE);
7426}
7427
7428TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7429 auto owner = User(mDispatcher, 10, 11);
7430 auto window = owner.createWindow();
7431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7432
7433 auto rando = User(mDispatcher, 20, 21);
7434 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7435 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7436
7437 setFocusedWindow(window);
7438 window->consumeFocusEvent(true);
7439
7440 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7441 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7442 window->assertNoEvents();
7443}
7444
7445TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7446 auto owner = User(mDispatcher, 10, 11);
7447 auto window = owner.createWindow();
7448 auto spy = owner.createWindow();
7449 spy->setSpy(true);
7450 spy->setTrustedOverlay(true);
7451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7452
7453 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7454 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7455 spy->consumeMotionDown();
7456 window->consumeMotionDown();
7457}
7458
7459TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7460 auto owner = User(mDispatcher, 10, 11);
7461 auto window = owner.createWindow();
7462
7463 auto rando = User(mDispatcher, 20, 21);
7464 auto randosSpy = rando.createWindow();
7465 randosSpy->setSpy(true);
7466 randosSpy->setTrustedOverlay(true);
7467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7468
7469 // The event is targeted at owner's window, so injection should succeed, but the spy should
7470 // not receive the event.
7471 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7472 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7473 randosSpy->assertNoEvents();
7474 window->consumeMotionDown();
7475}
7476
7477TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7478 auto owner = User(mDispatcher, 10, 11);
7479 auto window = owner.createWindow();
7480
7481 auto rando = User(mDispatcher, 20, 21);
7482 auto randosSpy = rando.createWindow();
7483 randosSpy->setSpy(true);
7484 randosSpy->setTrustedOverlay(true);
7485 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7486
7487 // A user that has injection permission can inject into any window.
7488 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7489 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7490 ADISPLAY_ID_DEFAULT));
7491 randosSpy->consumeMotionDown();
7492 window->consumeMotionDown();
7493
7494 setFocusedWindow(randosSpy);
7495 randosSpy->consumeFocusEvent(true);
7496
7497 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7498 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7499 window->assertNoEvents();
7500}
7501
7502TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7503 auto owner = User(mDispatcher, 10, 11);
7504 auto window = owner.createWindow();
7505
7506 auto rando = User(mDispatcher, 20, 21);
7507 auto randosWindow = rando.createWindow();
7508 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7509 randosWindow->setWatchOutsideTouch(true);
7510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7511
7512 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7513 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7514 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7515 window->consumeMotionDown();
7516 randosWindow->consumeMotionOutside();
7517}
7518
Garfield Tane84e6f92019-08-29 17:28:41 -07007519} // namespace android::inputdispatcher