blob: 35da4d890698a972ecf615f15d240a13facc8d37 [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 Pradhan5735a322022-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 Pradhan5735a322022-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 Pradhan5735a322022-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
Chris Yef59a2f42020-10-16 12:55:26 -0700415 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
416 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
417 const std::vector<float>& values) override {}
418
419 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
420 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000421
Chris Yefb552902021-02-03 17:18:37 -0800422 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
423
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600424 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 *outConfig = mConfig;
426 }
427
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600428 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700429 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800430 switch (inputEvent->getType()) {
431 case AINPUT_EVENT_TYPE_KEY: {
432 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800433 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800434 break;
435 }
436
437 case AINPUT_EVENT_TYPE_MOTION: {
438 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800439 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800440 break;
441 }
442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 return true;
444 }
445
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800446 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
447 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
448 // Clear intercept state when we handled the event.
449 mInterceptKeyTimeout = 0ms;
450 }
451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600453 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600455 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800456 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
457 // Clear intercept state so we could dispatch the event in next wake.
458 mInterceptKeyTimeout = 0ms;
459 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 }
461
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600462 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 return false;
464 }
465
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600466 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
467 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700468 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800469 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
470 * essentially a passthrough for notifySwitch.
471 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800472 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 }
474
Sean Stoutb4e0a592021-02-23 07:34:53 -0800475 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600477 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700478 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700479 mOnPointerDownToken = newToken;
480 }
481
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000482 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800483 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000484 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 mPointerCaptureChangedCondition.notify_all();
486 }
487
arthurhungf452d0b2021-01-06 00:19:52 +0800488 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
489 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800490 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800491 mDropTargetWindowToken = token;
492 }
493
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700494 void assertFilterInputEventWasCalledInternal(
495 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700496 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800497 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700498 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800499 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501};
502
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503// --- InputDispatcherTest ---
504
505class InputDispatcherTest : public testing::Test {
506protected:
507 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700508 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000510 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800512 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800513 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000514 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700515 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 }
517
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000518 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700519 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700521 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700523
524 /**
525 * Used for debugging when writing the test
526 */
527 void dumpDispatcherState() {
528 std::string dump;
529 mDispatcher->dump(dump);
530 std::stringstream ss(dump);
531 std::string to;
532
533 while (std::getline(ss, to, '\n')) {
534 ALOGE("%s", to.c_str());
535 }
536 }
Vishnu Nair958da932020-08-21 17:12:37 -0700537
chaviw3277faf2021-05-19 16:45:23 -0500538 void setFocusedWindow(const sp<WindowInfoHandle>& window,
539 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700540 FocusRequest request;
541 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000542 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700543 if (focusedWindow) {
544 request.focusedToken = focusedWindow->getToken();
545 }
546 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
547 request.displayId = window->getInfo()->displayId;
548 mDispatcher->setFocusedWindow(request);
549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550};
551
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
553 KeyEvent event;
554
555 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800556 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
557 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600558 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
559 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800560 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000561 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
562 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 << "Should reject key events with undefined action.";
564
565 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800566 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
567 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600568 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800569 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000570 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
571 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 << "Should reject key events with ACTION_MULTIPLE.";
573}
574
575TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
576 MotionEvent event;
577 PointerProperties pointerProperties[MAX_POINTERS + 1];
578 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800579 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 pointerProperties[i].clear();
581 pointerProperties[i].id = i;
582 pointerCoords[i].clear();
583 }
584
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800585 // Some constants commonly used below
586 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
587 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
588 constexpr int32_t metaState = AMETA_NONE;
589 constexpr MotionClassification classification = MotionClassification::NONE;
590
chaviw9eaa22c2020-07-01 16:21:27 -0700591 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800593 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700594 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
595 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700596 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
597 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700598 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000600 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
601 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject motion events with undefined action.";
603
604 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800606 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
607 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
608 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
609 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500610 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000612 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
613 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 << "Should reject motion events with pointer down index too large.";
615
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700617 AMOTION_EVENT_ACTION_POINTER_DOWN |
618 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700619 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
620 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700621 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500622 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800623 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000624 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
625 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 << "Should reject motion events with pointer down index too small.";
627
628 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800630 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
631 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
632 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
633 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500634 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000636 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
637 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 << "Should reject motion events with pointer up index too large.";
639
Garfield Tanfbe732e2020-01-24 11:26:14 -0800640 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 AMOTION_EVENT_ACTION_POINTER_UP |
642 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700643 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
644 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700645 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500646 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000648 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
649 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 << "Should reject motion events with pointer up index too small.";
651
652 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800653 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
654 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700655 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700656 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
657 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800659 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000660 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
661 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 << "Should reject motion events with 0 pointers.";
663
Garfield Tanfbe732e2020-01-24 11:26:14 -0800664 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
665 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700666 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700667 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
668 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700669 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800670 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000671 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
672 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 << "Should reject motion events with more than MAX_POINTERS pointers.";
674
675 // Rejects motion events with invalid pointer ids.
676 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800677 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
678 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700679 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700680 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
681 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700682 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800683 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000684 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
685 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 << "Should reject motion events with pointer ids less than 0.";
687
688 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800689 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
690 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700691 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700692 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
693 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700694 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800695 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000696 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
697 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
699
700 // Rejects motion events with duplicate pointer ids.
701 pointerProperties[0].id = 1;
702 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800703 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
704 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700705 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700706 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
707 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700708 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800709 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000710 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
711 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 << "Should reject motion events with duplicate pointer ids.";
713}
714
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800715/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
716
717TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
718 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800719 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800720 mDispatcher->notifyConfigurationChanged(&args);
721 ASSERT_TRUE(mDispatcher->waitForIdle());
722
723 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
724}
725
726TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800727 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
728 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800729 mDispatcher->notifySwitch(&args);
730
731 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
732 args.policyFlags |= POLICY_FLAG_TRUSTED;
733 mFakePolicy->assertNotifySwitchWasCalled(args);
734}
735
Arthur Hungb92218b2018-08-14 12:00:21 +0800736// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700737static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700738// Default input dispatching timeout if there is no focused application or paused window
739// from which to determine an appropriate dispatching timeout.
740static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
741 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
742 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800743
744class FakeApplicationHandle : public InputApplicationHandle {
745public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700746 FakeApplicationHandle() {
747 mInfo.name = "Fake Application";
748 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500749 mInfo.dispatchingTimeoutMillis =
750 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800752 virtual ~FakeApplicationHandle() {}
753
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000754 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700755
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500756 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
757 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700758 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800759};
760
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800761class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800762public:
Garfield Tan15601662020-09-22 15:32:38 -0700763 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800764 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700765 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800766 }
767
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800768 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700769 InputEvent* event;
770 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
771 if (!consumeSeq) {
772 return nullptr;
773 }
774 finishEvent(*consumeSeq);
775 return event;
776 }
777
778 /**
779 * Receive an event without acknowledging it.
780 * Return the sequence number that could later be used to send finished signal.
781 */
782 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800783 uint32_t consumeSeq;
784 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800785
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800786 std::chrono::time_point start = std::chrono::steady_clock::now();
787 status_t status = WOULD_BLOCK;
788 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800789 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800790 &event);
791 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
792 if (elapsed > 100ms) {
793 break;
794 }
795 }
796
797 if (status == WOULD_BLOCK) {
798 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700799 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800800 }
801
802 if (status != OK) {
803 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700804 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800805 }
806 if (event == nullptr) {
807 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700808 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800809 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700810 if (outEvent != nullptr) {
811 *outEvent = event;
812 }
813 return consumeSeq;
814 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700816 /**
817 * To be used together with "receiveEvent" to complete the consumption of an event.
818 */
819 void finishEvent(uint32_t consumeSeq) {
820 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
821 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800822 }
823
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000824 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
825 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
826 ASSERT_EQ(OK, status);
827 }
828
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000829 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
830 std::optional<int32_t> expectedDisplayId,
831 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800832 InputEvent* event = consume();
833
834 ASSERT_NE(nullptr, event) << mName.c_str()
835 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800836 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800838 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800839
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000840 if (expectedDisplayId.has_value()) {
841 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
842 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800843
Tiger Huang8664f8c2018-10-11 19:14:35 +0800844 switch (expectedEventType) {
845 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800846 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
847 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000848 if (expectedFlags.has_value()) {
849 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
850 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800851 break;
852 }
853 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800854 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000855 assertMotionAction(expectedAction, motionEvent.getAction());
856
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000857 if (expectedFlags.has_value()) {
858 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
859 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800860 break;
861 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100862 case AINPUT_EVENT_TYPE_FOCUS: {
863 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
864 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800865 case AINPUT_EVENT_TYPE_CAPTURE: {
866 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
867 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000868 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
869 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
870 }
arthurhungb89ccb02020-12-30 16:19:01 +0800871 case AINPUT_EVENT_TYPE_DRAG: {
872 FAIL() << "Use 'consumeDragEvent' for DRAG events";
873 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800874 default: {
875 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
876 }
877 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800878 }
879
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100880 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
881 InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of FOCUS event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890
891 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
892 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100893 }
894
Prabir Pradhan99987712020-11-10 18:43:05 -0800895 void consumeCaptureEvent(bool hasCapture) {
896 const InputEvent* event = consume();
897 ASSERT_NE(nullptr, event) << mName.c_str()
898 << ": consumer should have returned non-NULL event.";
899 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
900 << "Got " << inputEventTypeToString(event->getType())
901 << " event instead of CAPTURE event";
902
903 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
904 << mName.c_str() << ": event displayId should always be NONE.";
905
906 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
907 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
908 }
909
arthurhungb89ccb02020-12-30 16:19:01 +0800910 void consumeDragEvent(bool isExiting, float x, float y) {
911 const InputEvent* event = consume();
912 ASSERT_NE(nullptr, event) << mName.c_str()
913 << ": consumer should have returned non-NULL event.";
914 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
915 << "Got " << inputEventTypeToString(event->getType())
916 << " event instead of DRAG event";
917
918 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
919 << mName.c_str() << ": event displayId should always be NONE.";
920
921 const auto& dragEvent = static_cast<const DragEvent&>(*event);
922 EXPECT_EQ(isExiting, dragEvent.isExiting());
923 EXPECT_EQ(x, dragEvent.getX());
924 EXPECT_EQ(y, dragEvent.getY());
925 }
926
Antonio Kantekf16f2832021-09-28 04:39:20 +0000927 void consumeTouchModeEvent(bool inTouchMode) {
928 const InputEvent* event = consume();
929 ASSERT_NE(nullptr, event) << mName.c_str()
930 << ": consumer should have returned non-NULL event.";
931 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
932 << "Got " << inputEventTypeToString(event->getType())
933 << " event instead of TOUCH_MODE event";
934
935 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
936 << mName.c_str() << ": event displayId should always be NONE.";
937 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
938 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
939 }
940
chaviwd1c23182019-12-20 18:44:56 -0800941 void assertNoEvents() {
942 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943 if (event == nullptr) {
944 return;
945 }
946 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
947 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
948 ADD_FAILURE() << "Received key event "
949 << KeyEvent::actionToString(keyEvent.getAction());
950 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
951 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
952 ADD_FAILURE() << "Received motion event "
953 << MotionEvent::actionToString(motionEvent.getAction());
954 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
955 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
956 ADD_FAILURE() << "Received focus event, hasFocus = "
957 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800958 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
959 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
960 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
961 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000962 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
963 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
964 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
965 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 }
967 FAIL() << mName.c_str()
968 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800969 }
970
971 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
972
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800973 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
974
chaviwd1c23182019-12-20 18:44:56 -0800975protected:
976 std::unique_ptr<InputConsumer> mConsumer;
977 PreallocatedInputEventFactory mEventFactory;
978
979 std::string mName;
980};
981
chaviw3277faf2021-05-19 16:45:23 -0500982class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800983public:
984 static const int32_t WIDTH = 600;
985 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800986
Chris Yea209fde2020-07-22 13:54:51 -0700987 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700988 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500989 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800990 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500991 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700992 base::Result<std::unique_ptr<InputChannel>> channel =
993 dispatcher->createInputChannel(name);
994 token = (*channel)->getConnectionToken();
995 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800996 }
997
998 inputApplicationHandle->updateInfo();
999 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1000
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001001 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001002 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001003 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001004 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001005 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001006 mInfo.frameLeft = 0;
1007 mInfo.frameTop = 0;
1008 mInfo.frameRight = WIDTH;
1009 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001010 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001011 mInfo.globalScaleFactor = 1.0;
1012 mInfo.touchableRegion.clear();
1013 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001014 mInfo.ownerPid = WINDOW_PID;
1015 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001016 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001017 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001018 }
1019
Arthur Hungabbb9d82021-09-01 14:52:30 +00001020 sp<FakeWindowHandle> clone(
1021 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001022 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001023 sp<FakeWindowHandle> handle =
1024 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1025 displayId, mInfo.token);
1026 return handle;
1027 }
1028
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001029 void setTouchable(bool touchable) {
1030 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1031 }
chaviwd1c23182019-12-20 18:44:56 -08001032
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001033 void setFocusable(bool focusable) {
1034 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1035 }
1036
1037 void setVisible(bool visible) {
1038 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1039 }
Vishnu Nair958da932020-08-21 17:12:37 -07001040
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001041 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001042 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001043 }
1044
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001045 void setPaused(bool paused) {
1046 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1047 }
1048
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001049 void setPreventSplitting(bool preventSplitting) {
1050 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001051 }
1052
1053 void setSlippery(bool slippery) {
1054 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1055 }
1056
1057 void setWatchOutsideTouch(bool watchOutside) {
1058 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1059 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001060
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001061 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1062
1063 void setInterceptsStylus(bool interceptsStylus) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1065 }
1066
1067 void setDropInput(bool dropInput) {
1068 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1069 }
1070
1071 void setDropInputIfObscured(bool dropInputIfObscured) {
1072 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1073 }
1074
1075 void setNoInputChannel(bool noInputChannel) {
1076 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1077 }
1078
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001079 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1080
chaviw3277faf2021-05-19 16:45:23 -05001081 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001082
Bernardo Rufino7393d172021-02-26 13:56:11 +00001083 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1084
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001085 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001086 mInfo.frameLeft = frame.left;
1087 mInfo.frameTop = frame.top;
1088 mInfo.frameRight = frame.right;
1089 mInfo.frameBottom = frame.bottom;
1090 mInfo.touchableRegion.clear();
1091 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001092
1093 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1094 ui::Transform translate;
1095 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1096 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001097 }
1098
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1100
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001101 void setIsWallpaper(bool isWallpaper) {
1102 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1103 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001104
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001105 void setDupTouchToWallpaper(bool hasWallpaper) {
1106 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1107 }
chaviwd1c23182019-12-20 18:44:56 -08001108
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001109 void setTrustedOverlay(bool trustedOverlay) {
1110 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1111 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001112
chaviw9eaa22c2020-07-01 16:21:27 -07001113 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1114 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1115 }
1116
1117 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001118
yunho.shinf4a80b82020-11-16 21:13:57 +09001119 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1120
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001121 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1122 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1123 expectedFlags);
1124 }
1125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001126 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1127 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1128 }
1129
Svet Ganov5d3bc372020-01-26 23:11:07 -08001130 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001131 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001132 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1133 expectedFlags);
1134 }
1135
1136 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001137 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001138 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1139 expectedFlags);
1140 }
1141
1142 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001143 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001144 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1145 }
1146
1147 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1148 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001149 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1150 expectedFlags);
1151 }
1152
Svet Ganov5d3bc372020-01-26 23:11:07 -08001153 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001154 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1155 int32_t expectedFlags = 0) {
1156 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1157 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001158 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1159 }
1160
1161 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001162 int32_t expectedFlags = 0) {
1163 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1164 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001165 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1166 }
1167
1168 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001169 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001170 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1171 expectedFlags);
1172 }
1173
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001174 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1175 int32_t expectedFlags = 0) {
1176 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1177 expectedFlags);
1178 }
1179
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001180 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1181 int32_t expectedFlags = 0) {
1182 InputEvent* event = consume();
1183 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1184 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1185 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1186 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1187 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1188 }
1189
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001190 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1191 ASSERT_NE(mInputReceiver, nullptr)
1192 << "Cannot consume events from a window with no receiver";
1193 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1194 }
1195
Prabir Pradhan99987712020-11-10 18:43:05 -08001196 void consumeCaptureEvent(bool hasCapture) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeCaptureEvent(hasCapture);
1200 }
1201
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001202 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1203 std::optional<int32_t> expectedDisplayId,
1204 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001205 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1206 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1207 expectedFlags);
1208 }
1209
arthurhungb89ccb02020-12-30 16:19:01 +08001210 void consumeDragEvent(bool isExiting, float x, float y) {
1211 mInputReceiver->consumeDragEvent(isExiting, x, y);
1212 }
1213
Antonio Kantekf16f2832021-09-28 04:39:20 +00001214 void consumeTouchModeEvent(bool inTouchMode) {
1215 ASSERT_NE(mInputReceiver, nullptr)
1216 << "Cannot consume events from a window with no receiver";
1217 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1218 }
1219
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001221 if (mInputReceiver == nullptr) {
1222 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1223 return std::nullopt;
1224 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001225 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001226 }
1227
1228 void finishEvent(uint32_t sequenceNum) {
1229 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1230 mInputReceiver->finishEvent(sequenceNum);
1231 }
1232
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001233 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1234 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1235 mInputReceiver->sendTimeline(inputEventId, timeline);
1236 }
1237
chaviwaf87b3e2019-10-01 16:59:28 -07001238 InputEvent* consume() {
1239 if (mInputReceiver == nullptr) {
1240 return nullptr;
1241 }
1242 return mInputReceiver->consume();
1243 }
1244
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001245 MotionEvent* consumeMotion() {
1246 InputEvent* event = consume();
1247 if (event == nullptr) {
1248 ADD_FAILURE() << "Consume failed : no event";
1249 return nullptr;
1250 }
1251 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1252 ADD_FAILURE() << "Instead of motion event, got "
1253 << inputEventTypeToString(event->getType());
1254 return nullptr;
1255 }
1256 return static_cast<MotionEvent*>(event);
1257 }
1258
Arthur Hungb92218b2018-08-14 12:00:21 +08001259 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001260 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001261 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001262 return; // Can't receive events if the window does not have input channel
1263 }
1264 ASSERT_NE(nullptr, mInputReceiver)
1265 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001266 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001267 }
1268
chaviwaf87b3e2019-10-01 16:59:28 -07001269 sp<IBinder> getToken() { return mInfo.token; }
1270
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001271 const std::string& getName() { return mName; }
1272
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001273 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1274 mInfo.ownerPid = ownerPid;
1275 mInfo.ownerUid = ownerUid;
1276 }
1277
Prabir Pradhanedd96402022-02-15 01:46:16 -08001278 int32_t getPid() const { return mInfo.ownerPid; }
1279
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001280 void destroyReceiver() { mInputReceiver = nullptr; }
1281
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001282 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1283
chaviwd1c23182019-12-20 18:44:56 -08001284private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001285 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001286 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001287 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001288};
1289
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001290std::atomic<int32_t> FakeWindowHandle::sId{1};
1291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001293 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001294 int32_t displayId = ADISPLAY_ID_NONE,
1295 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001296 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001297 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1298 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001299 KeyEvent event;
1300 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1301
1302 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001303 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001304 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1305 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001306
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001307 if (!allowKeyRepeat) {
1308 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1309 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001310 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001311 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001312}
1313
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001314static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001315 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001316 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1317}
1318
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001319// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1320// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1321// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001322static InputEventInjectionResult injectKeyDownNoRepeat(
1323 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001324 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1325 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1326 /* allowKeyRepeat */ false);
1327}
1328
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001329static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001330 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001331 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1332}
1333
Garfield Tandf26e862020-07-01 20:18:19 -07001334class PointerBuilder {
1335public:
1336 PointerBuilder(int32_t id, int32_t toolType) {
1337 mProperties.clear();
1338 mProperties.id = id;
1339 mProperties.toolType = toolType;
1340 mCoords.clear();
1341 }
1342
1343 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1344
1345 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1346
1347 PointerBuilder& axis(int32_t axis, float value) {
1348 mCoords.setAxisValue(axis, value);
1349 return *this;
1350 }
1351
1352 PointerProperties buildProperties() const { return mProperties; }
1353
1354 PointerCoords buildCoords() const { return mCoords; }
1355
1356private:
1357 PointerProperties mProperties;
1358 PointerCoords mCoords;
1359};
1360
1361class MotionEventBuilder {
1362public:
1363 MotionEventBuilder(int32_t action, int32_t source) {
1364 mAction = action;
1365 mSource = source;
1366 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1367 }
1368
1369 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1370 mEventTime = eventTime;
1371 return *this;
1372 }
1373
1374 MotionEventBuilder& displayId(int32_t displayId) {
1375 mDisplayId = displayId;
1376 return *this;
1377 }
1378
1379 MotionEventBuilder& actionButton(int32_t actionButton) {
1380 mActionButton = actionButton;
1381 return *this;
1382 }
1383
arthurhung6d4bed92021-03-17 11:59:33 +08001384 MotionEventBuilder& buttonState(int32_t buttonState) {
1385 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001386 return *this;
1387 }
1388
1389 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1390 mRawXCursorPosition = rawXCursorPosition;
1391 return *this;
1392 }
1393
1394 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1395 mRawYCursorPosition = rawYCursorPosition;
1396 return *this;
1397 }
1398
1399 MotionEventBuilder& pointer(PointerBuilder pointer) {
1400 mPointers.push_back(pointer);
1401 return *this;
1402 }
1403
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001404 MotionEventBuilder& addFlag(uint32_t flags) {
1405 mFlags |= flags;
1406 return *this;
1407 }
1408
Garfield Tandf26e862020-07-01 20:18:19 -07001409 MotionEvent build() {
1410 std::vector<PointerProperties> pointerProperties;
1411 std::vector<PointerCoords> pointerCoords;
1412 for (const PointerBuilder& pointer : mPointers) {
1413 pointerProperties.push_back(pointer.buildProperties());
1414 pointerCoords.push_back(pointer.buildCoords());
1415 }
1416
1417 // Set mouse cursor position for the most common cases to avoid boilerplate.
1418 if (mSource == AINPUT_SOURCE_MOUSE &&
1419 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1420 mPointers.size() == 1) {
1421 mRawXCursorPosition = pointerCoords[0].getX();
1422 mRawYCursorPosition = pointerCoords[0].getY();
1423 }
1424
1425 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001426 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001427 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001428 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001429 mButtonState, MotionClassification::NONE, identityTransform,
1430 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001431 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1432 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001433
1434 return event;
1435 }
1436
1437private:
1438 int32_t mAction;
1439 int32_t mSource;
1440 nsecs_t mEventTime;
1441 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1442 int32_t mActionButton{0};
1443 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001444 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001445 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1446 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1447
1448 std::vector<PointerBuilder> mPointers;
1449};
1450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001452 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001453 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001454 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1455 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1456 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1457 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001458}
1459
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001461 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001462 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001463 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001464 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1465 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001467 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1468 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001469 MotionEvent event = MotionEventBuilder(action, source)
1470 .displayId(displayId)
1471 .eventTime(eventTime)
1472 .rawXCursorPosition(cursorPosition.x)
1473 .rawYCursorPosition(cursorPosition.y)
1474 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1475 .x(position.x)
1476 .y(position.y))
1477 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001478
1479 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001480 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1481 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001482}
1483
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001484static InputEventInjectionResult injectMotionDown(
1485 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1486 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001487 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001488}
1489
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001490static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001491 int32_t source, int32_t displayId,
1492 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001493 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001494}
1495
Jackal Guof9696682018-10-05 12:23:23 +08001496static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1497 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1498 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001499 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1500 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1501 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001502
1503 return args;
1504}
1505
chaviwd1c23182019-12-20 18:44:56 -08001506static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1507 const std::vector<PointF>& points) {
1508 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001509 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1510 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1511 }
1512
chaviwd1c23182019-12-20 18:44:56 -08001513 PointerProperties pointerProperties[pointerCount];
1514 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001515
chaviwd1c23182019-12-20 18:44:56 -08001516 for (size_t i = 0; i < pointerCount; i++) {
1517 pointerProperties[i].clear();
1518 pointerProperties[i].id = i;
1519 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001520
chaviwd1c23182019-12-20 18:44:56 -08001521 pointerCoords[i].clear();
1522 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1523 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1524 }
Jackal Guof9696682018-10-05 12:23:23 +08001525
1526 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1527 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001528 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001529 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1530 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001531 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1532 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001533 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1534 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001535
1536 return args;
1537}
1538
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001539static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1540 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1541}
1542
chaviwd1c23182019-12-20 18:44:56 -08001543static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1544 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1545}
1546
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001547static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1548 const PointerCaptureRequest& request) {
1549 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001550}
1551
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001552/**
1553 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1554 * broken channel.
1555 */
1556TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1557 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1558 sp<FakeWindowHandle> window =
1559 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1560 ADISPLAY_ID_DEFAULT);
1561
1562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1563
1564 // Window closes its channel, but the window remains.
1565 window->destroyReceiver();
1566 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1567}
1568
Arthur Hungb92218b2018-08-14 12:00:21 +08001569TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001570 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001571 sp<FakeWindowHandle> window =
1572 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001573
Arthur Hung72d8dc32020-03-28 00:48:39 +00001574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1576 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001578
1579 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001580 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001581}
1582
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001583TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1584 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1585 sp<FakeWindowHandle> window =
1586 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1587
1588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1589 // Inject a MotionEvent to an unknown display.
1590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1591 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1593
1594 // Window should receive motion event.
1595 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1596}
1597
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001598/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001599 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001600 * This test serves as a sanity check for the next test, where setInputWindows is
1601 * called twice.
1602 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001603TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001604 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001605 sp<FakeWindowHandle> window =
1606 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1607 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001608
1609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1612 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001614
1615 // Window should receive motion event.
1616 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1617}
1618
1619/**
1620 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001621 */
1622TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001624 sp<FakeWindowHandle> window =
1625 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1626 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001627
1628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001631 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1632 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001633 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001634
1635 // Window should receive motion event.
1636 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1637}
1638
Arthur Hungb92218b2018-08-14 12:00:21 +08001639// The foreground window should receive the first touch down event.
1640TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001641 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001642 sp<FakeWindowHandle> windowTop =
1643 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1644 sp<FakeWindowHandle> windowSecond =
1645 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001646
Arthur Hung72d8dc32020-03-28 00:48:39 +00001647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1650 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001651
1652 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001653 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001654 windowSecond->assertNoEvents();
1655}
1656
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001657/**
1658 * Two windows: A top window, and a wallpaper behind the window.
1659 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1660 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001661 * 1. foregroundWindow <-- dup touch to wallpaper
1662 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001663 */
1664TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1665 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1666 sp<FakeWindowHandle> foregroundWindow =
1667 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001668 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001669 sp<FakeWindowHandle> wallpaperWindow =
1670 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001671 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001672 constexpr int expectedWallpaperFlags =
1673 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1674
1675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1676 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1677 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1678 {100, 200}))
1679 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1680
1681 // Both foreground window and its wallpaper should receive the touch down
1682 foregroundWindow->consumeMotionDown();
1683 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1684
1685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1686 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1687 ADISPLAY_ID_DEFAULT, {110, 200}))
1688 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1689
1690 foregroundWindow->consumeMotionMove();
1691 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1692
1693 // Now the foreground window goes away, but the wallpaper stays
1694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1695 foregroundWindow->consumeMotionCancel();
1696 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1697 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1698}
1699
1700/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001701 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1702 * with the following differences:
1703 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1704 * clean up the connection.
1705 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1706 * Ensure that there's no crash in the dispatcher.
1707 */
1708TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1710 sp<FakeWindowHandle> foregroundWindow =
1711 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001712 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001713 sp<FakeWindowHandle> wallpaperWindow =
1714 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001715 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001716 constexpr int expectedWallpaperFlags =
1717 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1718
1719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1720 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1721 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1722 {100, 200}))
1723 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1724
1725 // Both foreground window and its wallpaper should receive the touch down
1726 foregroundWindow->consumeMotionDown();
1727 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1728
1729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1730 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1731 ADISPLAY_ID_DEFAULT, {110, 200}))
1732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1733
1734 foregroundWindow->consumeMotionMove();
1735 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1736
1737 // Wallpaper closes its channel, but the window remains.
1738 wallpaperWindow->destroyReceiver();
1739 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1740
1741 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1742 // is no longer valid.
1743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1744 foregroundWindow->consumeMotionCancel();
1745}
1746
1747/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001748 * A single window that receives touch (on top), and a wallpaper window underneath it.
1749 * The top window gets a multitouch gesture.
1750 * Ensure that wallpaper gets the same gesture.
1751 */
1752TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1753 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1754 sp<FakeWindowHandle> window =
1755 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001756 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001757
1758 sp<FakeWindowHandle> wallpaperWindow =
1759 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001760 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001761 constexpr int expectedWallpaperFlags =
1762 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1763
1764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1765
1766 // Touch down on top window
1767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1768 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1769 {100, 100}))
1770 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1771
1772 // Both top window and its wallpaper should receive the touch down
1773 window->consumeMotionDown();
1774 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1775
1776 // Second finger down on the top window
1777 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001778 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001779 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1780 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1781 .x(100)
1782 .y(100))
1783 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1784 .x(150)
1785 .y(150))
1786 .build();
1787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1788 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1789 InputEventInjectionSync::WAIT_FOR_RESULT))
1790 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1791
1792 window->consumeMotionPointerDown(1 /* pointerIndex */);
1793 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1794 expectedWallpaperFlags);
1795 window->assertNoEvents();
1796 wallpaperWindow->assertNoEvents();
1797}
1798
1799/**
1800 * Two windows: a window on the left and window on the right.
1801 * A third window, wallpaper, is behind both windows, and spans both top windows.
1802 * The first touch down goes to the left window. A second pointer touches down on the right window.
1803 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1804 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1805 * ACTION_POINTER_DOWN(1).
1806 */
1807TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1808 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1809 sp<FakeWindowHandle> leftWindow =
1810 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1811 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001812 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001813
1814 sp<FakeWindowHandle> rightWindow =
1815 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1816 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001817 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001818
1819 sp<FakeWindowHandle> wallpaperWindow =
1820 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1821 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001822 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001823 constexpr int expectedWallpaperFlags =
1824 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1825
1826 mDispatcher->setInputWindows(
1827 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1828
1829 // Touch down on left window
1830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1831 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1832 {100, 100}))
1833 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1834
1835 // Both foreground window and its wallpaper should receive the touch down
1836 leftWindow->consumeMotionDown();
1837 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1838
1839 // Second finger down on the right window
1840 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001841 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001842 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1843 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1844 .x(100)
1845 .y(100))
1846 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1847 .x(300)
1848 .y(100))
1849 .build();
1850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1851 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1852 InputEventInjectionSync::WAIT_FOR_RESULT))
1853 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1854
1855 leftWindow->consumeMotionMove();
1856 // Since the touch is split, right window gets ACTION_DOWN
1857 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1858 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1859 expectedWallpaperFlags);
1860
1861 // Now, leftWindow, which received the first finger, disappears.
1862 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1863 leftWindow->consumeMotionCancel();
1864 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1865 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1866
1867 // The pointer that's still down on the right window moves, and goes to the right window only.
1868 // As far as the dispatcher's concerned though, both pointers are still present.
1869 const MotionEvent secondFingerMoveEvent =
1870 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1871 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1872 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1873 .x(100)
1874 .y(100))
1875 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1876 .x(310)
1877 .y(110))
1878 .build();
1879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1880 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1881 InputEventInjectionSync::WAIT_FOR_RESULT));
1882 rightWindow->consumeMotionMove();
1883
1884 leftWindow->assertNoEvents();
1885 rightWindow->assertNoEvents();
1886 wallpaperWindow->assertNoEvents();
1887}
1888
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001889/**
1890 * On the display, have a single window, and also an area where there's no window.
1891 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1892 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1893 */
1894TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1895 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1896 sp<FakeWindowHandle> window =
1897 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1898
1899 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1900 NotifyMotionArgs args;
1901
1902 // Touch down on the empty space
1903 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1904
1905 mDispatcher->waitForIdle();
1906 window->assertNoEvents();
1907
1908 // Now touch down on the window with another pointer
1909 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1910 mDispatcher->waitForIdle();
1911 window->consumeMotionDown();
1912}
1913
1914/**
1915 * Same test as above, but instead of touching the empty space, the first touch goes to
1916 * non-touchable window.
1917 */
1918TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1919 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1920 sp<FakeWindowHandle> window1 =
1921 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1922 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1923 window1->setTouchable(false);
1924 sp<FakeWindowHandle> window2 =
1925 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1926 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1927
1928 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1929
1930 NotifyMotionArgs args;
1931 // Touch down on the non-touchable window
1932 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1933
1934 mDispatcher->waitForIdle();
1935 window1->assertNoEvents();
1936 window2->assertNoEvents();
1937
1938 // Now touch down on the window with another pointer
1939 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1940 mDispatcher->waitForIdle();
1941 window2->consumeMotionDown();
1942}
1943
Garfield Tandf26e862020-07-01 20:18:19 -07001944TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001945 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001946 sp<FakeWindowHandle> windowLeft =
1947 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1948 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001949 sp<FakeWindowHandle> windowRight =
1950 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1951 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001952
1953 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1954
1955 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1956
1957 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001959 injectMotionEvent(mDispatcher,
1960 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1961 AINPUT_SOURCE_MOUSE)
1962 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1963 .x(900)
1964 .y(400))
1965 .build()));
1966 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1967 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1968 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1969 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1970
1971 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001973 injectMotionEvent(mDispatcher,
1974 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1975 AINPUT_SOURCE_MOUSE)
1976 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1977 .x(300)
1978 .y(400))
1979 .build()));
1980 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1981 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1982 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1983 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1984 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1985 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1986
1987 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001989 injectMotionEvent(mDispatcher,
1990 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1991 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1992 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1993 .x(300)
1994 .y(400))
1995 .build()));
1996 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001999 injectMotionEvent(mDispatcher,
2000 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2001 AINPUT_SOURCE_MOUSE)
2002 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2003 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2004 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2005 .x(300)
2006 .y(400))
2007 .build()));
2008 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2009 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2010
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002012 injectMotionEvent(mDispatcher,
2013 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2014 AINPUT_SOURCE_MOUSE)
2015 .buttonState(0)
2016 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2017 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2018 .x(300)
2019 .y(400))
2020 .build()));
2021 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2022 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2023
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002025 injectMotionEvent(mDispatcher,
2026 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2027 .buttonState(0)
2028 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2029 .x(300)
2030 .y(400))
2031 .build()));
2032 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2033
2034 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002036 injectMotionEvent(mDispatcher,
2037 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2038 AINPUT_SOURCE_MOUSE)
2039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2040 .x(900)
2041 .y(400))
2042 .build()));
2043 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2044 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2045 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2046 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2047 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2048 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2049}
2050
2051// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2052// directly in this test.
2053TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002054 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002055 sp<FakeWindowHandle> window =
2056 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2057 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002058
2059 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2060
2061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2062
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002064 injectMotionEvent(mDispatcher,
2065 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2066 AINPUT_SOURCE_MOUSE)
2067 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2068 .x(300)
2069 .y(400))
2070 .build()));
2071 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2072 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2073
2074 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002076 injectMotionEvent(mDispatcher,
2077 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2078 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2079 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2080 .x(300)
2081 .y(400))
2082 .build()));
2083 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2084
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002085 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002086 injectMotionEvent(mDispatcher,
2087 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2088 AINPUT_SOURCE_MOUSE)
2089 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2090 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2091 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2092 .x(300)
2093 .y(400))
2094 .build()));
2095 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2096 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2097
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002099 injectMotionEvent(mDispatcher,
2100 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2101 AINPUT_SOURCE_MOUSE)
2102 .buttonState(0)
2103 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2104 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2105 .x(300)
2106 .y(400))
2107 .build()));
2108 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2109 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2110
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002112 injectMotionEvent(mDispatcher,
2113 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2114 .buttonState(0)
2115 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2116 .x(300)
2117 .y(400))
2118 .build()));
2119 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2120
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002122 injectMotionEvent(mDispatcher,
2123 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2124 AINPUT_SOURCE_MOUSE)
2125 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2126 .x(300)
2127 .y(400))
2128 .build()));
2129 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2130 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2131}
2132
Garfield Tan00f511d2019-06-12 16:55:40 -07002133TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002134 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002135
2136 sp<FakeWindowHandle> windowLeft =
2137 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2138 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002139 sp<FakeWindowHandle> windowRight =
2140 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2141 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002142
2143 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2144
Arthur Hung72d8dc32020-03-28 00:48:39 +00002145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002146
2147 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2148 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002149 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002150 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002151 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002152 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002153 windowRight->assertNoEvents();
2154}
2155
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002156TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002158 sp<FakeWindowHandle> window =
2159 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002160 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002161
Arthur Hung72d8dc32020-03-28 00:48:39 +00002162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002163 setFocusedWindow(window);
2164
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002165 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002166
2167 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2168 mDispatcher->notifyKey(&keyArgs);
2169
2170 // Window should receive key down event.
2171 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2172
2173 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2174 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002175 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002176 mDispatcher->notifyDeviceReset(&args);
2177 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2178 AKEY_EVENT_FLAG_CANCELED);
2179}
2180
2181TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002182 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002183 sp<FakeWindowHandle> window =
2184 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2185
Arthur Hung72d8dc32020-03-28 00:48:39 +00002186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002187
2188 NotifyMotionArgs motionArgs =
2189 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2190 ADISPLAY_ID_DEFAULT);
2191 mDispatcher->notifyMotion(&motionArgs);
2192
2193 // Window should receive motion down event.
2194 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2195
2196 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2197 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002198 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002199 mDispatcher->notifyDeviceReset(&args);
2200 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2201 0 /*expectedFlags*/);
2202}
2203
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002204TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2205 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2206 sp<FakeWindowHandle> window =
2207 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2208 window->setFocusable(true);
2209
2210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2211 setFocusedWindow(window);
2212
2213 window->consumeFocusEvent(true);
2214
2215 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2216 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2217 const nsecs_t injectTime = keyArgs.eventTime;
2218 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2219 mDispatcher->notifyKey(&keyArgs);
2220 // The dispatching time should be always greater than or equal to intercept key timeout.
2221 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2222 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2223 std::chrono::nanoseconds(interceptKeyTimeout).count());
2224}
2225
2226TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2228 sp<FakeWindowHandle> window =
2229 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2230 window->setFocusable(true);
2231
2232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2233 setFocusedWindow(window);
2234
2235 window->consumeFocusEvent(true);
2236
2237 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2238 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2239 mFakePolicy->setInterceptKeyTimeout(150ms);
2240 mDispatcher->notifyKey(&keyDown);
2241 mDispatcher->notifyKey(&keyUp);
2242
2243 // Window should receive key event immediately when same key up.
2244 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2245 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2246}
2247
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002248/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002249 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2250 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2251 * ACTION_OUTSIDE event is sent per gesture.
2252 */
2253TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2254 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2255 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2256 sp<FakeWindowHandle> window =
2257 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2258 window->setWatchOutsideTouch(true);
2259 window->setFrame(Rect{0, 0, 100, 100});
2260 sp<FakeWindowHandle> secondWindow =
2261 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2262 secondWindow->setFrame(Rect{100, 100, 200, 200});
2263 sp<FakeWindowHandle> thirdWindow =
2264 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2265 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2267
2268 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2269 NotifyMotionArgs motionArgs =
2270 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2271 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2272 mDispatcher->notifyMotion(&motionArgs);
2273 window->assertNoEvents();
2274 secondWindow->assertNoEvents();
2275
2276 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2277 // Now, `window` should get ACTION_OUTSIDE.
2278 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2279 {PointF{-10, -10}, PointF{105, 105}});
2280 mDispatcher->notifyMotion(&motionArgs);
2281 window->consumeMotionOutside();
2282 secondWindow->consumeMotionDown();
2283 thirdWindow->assertNoEvents();
2284
2285 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2286 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2287 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2288 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2289 mDispatcher->notifyMotion(&motionArgs);
2290 window->assertNoEvents();
2291 secondWindow->consumeMotionMove();
2292 thirdWindow->consumeMotionDown();
2293}
2294
2295/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002296 * Ensure the correct coordinate spaces are used by InputDispatcher.
2297 *
2298 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2299 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2300 * space.
2301 */
2302class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2303public:
2304 void SetUp() override {
2305 InputDispatcherTest::SetUp();
2306 mDisplayInfos.clear();
2307 mWindowInfos.clear();
2308 }
2309
2310 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2311 gui::DisplayInfo info;
2312 info.displayId = displayId;
2313 info.transform = transform;
2314 mDisplayInfos.push_back(std::move(info));
2315 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2316 }
2317
2318 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2319 mWindowInfos.push_back(*windowHandle->getInfo());
2320 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2321 }
2322
2323 // Set up a test scenario where the display has a scaled projection and there are two windows
2324 // on the display.
2325 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2326 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2327 // respectively.
2328 ui::Transform displayTransform;
2329 displayTransform.set(2, 0, 0, 4);
2330 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2331
2332 std::shared_ptr<FakeApplicationHandle> application =
2333 std::make_shared<FakeApplicationHandle>();
2334
2335 // Add two windows to the display. Their frames are represented in the display space.
2336 sp<FakeWindowHandle> firstWindow =
2337 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002338 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2339 addWindow(firstWindow);
2340
2341 sp<FakeWindowHandle> secondWindow =
2342 new FakeWindowHandle(application, mDispatcher, "Second Window",
2343 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002344 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2345 addWindow(secondWindow);
2346 return {std::move(firstWindow), std::move(secondWindow)};
2347 }
2348
2349private:
2350 std::vector<gui::DisplayInfo> mDisplayInfos;
2351 std::vector<gui::WindowInfo> mWindowInfos;
2352};
2353
2354TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2355 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2356 // Send down to the first window. The point is represented in the display space. The point is
2357 // selected so that if the hit test was done with the transform applied to it, then it would
2358 // end up in the incorrect window.
2359 NotifyMotionArgs downMotionArgs =
2360 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2361 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2362 mDispatcher->notifyMotion(&downMotionArgs);
2363
2364 firstWindow->consumeMotionDown();
2365 secondWindow->assertNoEvents();
2366}
2367
2368// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2369// the event should be treated as being in the logical display space.
2370TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2371 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2372 // Send down to the first window. The point is represented in the logical display space. The
2373 // point is selected so that if the hit test was done in logical display space, then it would
2374 // end up in the incorrect window.
2375 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2376 PointF{75 * 2, 55 * 4});
2377
2378 firstWindow->consumeMotionDown();
2379 secondWindow->assertNoEvents();
2380}
2381
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002382// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2383// event should be treated as being in the logical display space.
2384TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2385 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2386
2387 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2388 ui::Transform injectedEventTransform;
2389 injectedEventTransform.set(matrix);
2390 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2391 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2392
2393 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2394 .displayId(ADISPLAY_ID_DEFAULT)
2395 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2396 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2397 .x(untransformedPoint.x)
2398 .y(untransformedPoint.y))
2399 .build();
2400 event.transform(matrix);
2401
2402 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2403 InputEventInjectionSync::WAIT_FOR_RESULT);
2404
2405 firstWindow->consumeMotionDown();
2406 secondWindow->assertNoEvents();
2407}
2408
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002409TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2410 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2411
2412 // Send down to the second window.
2413 NotifyMotionArgs downMotionArgs =
2414 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2415 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2416 mDispatcher->notifyMotion(&downMotionArgs);
2417
2418 firstWindow->assertNoEvents();
2419 const MotionEvent* event = secondWindow->consumeMotion();
2420 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2421
2422 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2423 EXPECT_EQ(300, event->getRawX(0));
2424 EXPECT_EQ(880, event->getRawY(0));
2425
2426 // Ensure that the x and y values are in the window's coordinate space.
2427 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2428 // the logical display space. This will be the origin of the window space.
2429 EXPECT_EQ(100, event->getX(0));
2430 EXPECT_EQ(80, event->getY(0));
2431}
2432
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002433using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2434 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002435
2436class TransferTouchFixture : public InputDispatcherTest,
2437 public ::testing::WithParamInterface<TransferFunction> {};
2438
2439TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002441
2442 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002443 sp<FakeWindowHandle> firstWindow =
2444 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2445 sp<FakeWindowHandle> secondWindow =
2446 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002447
2448 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002449 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002450
2451 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002452 NotifyMotionArgs downMotionArgs =
2453 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2454 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002455 mDispatcher->notifyMotion(&downMotionArgs);
2456 // Only the first window should get the down event
2457 firstWindow->consumeMotionDown();
2458 secondWindow->assertNoEvents();
2459
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002460 // Transfer touch to the second window
2461 TransferFunction f = GetParam();
2462 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2463 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002464 // The first window gets cancel and the second gets down
2465 firstWindow->consumeMotionCancel();
2466 secondWindow->consumeMotionDown();
2467
2468 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002469 NotifyMotionArgs upMotionArgs =
2470 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2471 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002472 mDispatcher->notifyMotion(&upMotionArgs);
2473 // The first window gets no events and the second gets up
2474 firstWindow->assertNoEvents();
2475 secondWindow->consumeMotionUp();
2476}
2477
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002478/**
2479 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2480 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2481 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2482 * natural to the user.
2483 * In this test, we are sending a pointer to both spy window and first window. We then try to
2484 * transfer touch to the second window. The dispatcher should identify the first window as the
2485 * one that should lose the gesture, and therefore the action should be to move the gesture from
2486 * the first window to the second.
2487 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2488 * the other API, as well.
2489 */
2490TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2491 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2492
2493 // Create a couple of windows + a spy window
2494 sp<FakeWindowHandle> spyWindow =
2495 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2496 spyWindow->setTrustedOverlay(true);
2497 spyWindow->setSpy(true);
2498 sp<FakeWindowHandle> firstWindow =
2499 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2500 sp<FakeWindowHandle> secondWindow =
2501 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2502
2503 // Add the windows to the dispatcher
2504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2505
2506 // Send down to the first window
2507 NotifyMotionArgs downMotionArgs =
2508 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2509 ADISPLAY_ID_DEFAULT);
2510 mDispatcher->notifyMotion(&downMotionArgs);
2511 // Only the first window and spy should get the down event
2512 spyWindow->consumeMotionDown();
2513 firstWindow->consumeMotionDown();
2514
2515 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2516 // if f === 'transferTouch'.
2517 TransferFunction f = GetParam();
2518 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2519 ASSERT_TRUE(success);
2520 // The first window gets cancel and the second gets down
2521 firstWindow->consumeMotionCancel();
2522 secondWindow->consumeMotionDown();
2523
2524 // Send up event to the second window
2525 NotifyMotionArgs upMotionArgs =
2526 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2527 ADISPLAY_ID_DEFAULT);
2528 mDispatcher->notifyMotion(&upMotionArgs);
2529 // The first window gets no events and the second+spy get up
2530 firstWindow->assertNoEvents();
2531 spyWindow->consumeMotionUp();
2532 secondWindow->consumeMotionUp();
2533}
2534
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002535TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002536 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002537
2538 PointF touchPoint = {10, 10};
2539
2540 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002541 sp<FakeWindowHandle> firstWindow =
2542 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002543 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002544 sp<FakeWindowHandle> secondWindow =
2545 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002546 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002547
2548 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002550
2551 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002552 NotifyMotionArgs downMotionArgs =
2553 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2554 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002555 mDispatcher->notifyMotion(&downMotionArgs);
2556 // Only the first window should get the down event
2557 firstWindow->consumeMotionDown();
2558 secondWindow->assertNoEvents();
2559
2560 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002561 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002562 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002563 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002564 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2565 // Only the first window should get the pointer down event
2566 firstWindow->consumeMotionPointerDown(1);
2567 secondWindow->assertNoEvents();
2568
2569 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002570 TransferFunction f = GetParam();
2571 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2572 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002573 // The first window gets cancel and the second gets down and pointer down
2574 firstWindow->consumeMotionCancel();
2575 secondWindow->consumeMotionDown();
2576 secondWindow->consumeMotionPointerDown(1);
2577
2578 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002579 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002580 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002581 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002582 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2583 // The first window gets nothing and the second gets pointer up
2584 firstWindow->assertNoEvents();
2585 secondWindow->consumeMotionPointerUp(1);
2586
2587 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002588 NotifyMotionArgs upMotionArgs =
2589 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2590 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002591 mDispatcher->notifyMotion(&upMotionArgs);
2592 // The first window gets nothing and the second gets up
2593 firstWindow->assertNoEvents();
2594 secondWindow->consumeMotionUp();
2595}
2596
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002597// For the cases of single pointer touch and two pointers non-split touch, the api's
2598// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2599// for the case where there are multiple pointers split across several windows.
2600INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2601 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002602 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2603 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002604 return dispatcher->transferTouch(destChannelToken,
2605 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002606 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002607 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2608 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002609 return dispatcher->transferTouchFocus(from, to,
2610 false /*isDragAndDrop*/);
2611 }));
2612
Svet Ganov5d3bc372020-01-26 23:11:07 -08002613TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002614 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002615
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002616 sp<FakeWindowHandle> firstWindow =
2617 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002618 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002619
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002620 sp<FakeWindowHandle> secondWindow =
2621 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002622 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002623
2624 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002626
2627 PointF pointInFirst = {300, 200};
2628 PointF pointInSecond = {300, 600};
2629
2630 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002631 NotifyMotionArgs firstDownMotionArgs =
2632 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2633 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002634 mDispatcher->notifyMotion(&firstDownMotionArgs);
2635 // Only the first window should get the down event
2636 firstWindow->consumeMotionDown();
2637 secondWindow->assertNoEvents();
2638
2639 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002640 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002641 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002642 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002643 mDispatcher->notifyMotion(&secondDownMotionArgs);
2644 // The first window gets a move and the second a down
2645 firstWindow->consumeMotionMove();
2646 secondWindow->consumeMotionDown();
2647
2648 // Transfer touch focus to the second window
2649 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2650 // The first window gets cancel and the new gets pointer down (it already saw down)
2651 firstWindow->consumeMotionCancel();
2652 secondWindow->consumeMotionPointerDown(1);
2653
2654 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002655 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002656 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002657 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002658 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2659 // The first window gets nothing and the second gets pointer up
2660 firstWindow->assertNoEvents();
2661 secondWindow->consumeMotionPointerUp(1);
2662
2663 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002664 NotifyMotionArgs upMotionArgs =
2665 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2666 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002667 mDispatcher->notifyMotion(&upMotionArgs);
2668 // The first window gets nothing and the second gets up
2669 firstWindow->assertNoEvents();
2670 secondWindow->consumeMotionUp();
2671}
2672
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002673// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2674// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2675// touch is not supported, so the touch should continue on those windows and the transferred-to
2676// window should get nothing.
2677TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2678 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2679
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002680 sp<FakeWindowHandle> firstWindow =
2681 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2682 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002683
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002684 sp<FakeWindowHandle> secondWindow =
2685 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2686 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002687
2688 // Add the windows to the dispatcher
2689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2690
2691 PointF pointInFirst = {300, 200};
2692 PointF pointInSecond = {300, 600};
2693
2694 // Send down to the first window
2695 NotifyMotionArgs firstDownMotionArgs =
2696 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2697 ADISPLAY_ID_DEFAULT, {pointInFirst});
2698 mDispatcher->notifyMotion(&firstDownMotionArgs);
2699 // Only the first window should get the down event
2700 firstWindow->consumeMotionDown();
2701 secondWindow->assertNoEvents();
2702
2703 // Send down to the second window
2704 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002705 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002706 {pointInFirst, pointInSecond});
2707 mDispatcher->notifyMotion(&secondDownMotionArgs);
2708 // The first window gets a move and the second a down
2709 firstWindow->consumeMotionMove();
2710 secondWindow->consumeMotionDown();
2711
2712 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002713 const bool transferred =
2714 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002715 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2716 ASSERT_FALSE(transferred);
2717 firstWindow->assertNoEvents();
2718 secondWindow->assertNoEvents();
2719
2720 // The rest of the dispatch should proceed as normal
2721 // Send pointer up to the second window
2722 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002723 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002724 {pointInFirst, pointInSecond});
2725 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2726 // The first window gets MOVE and the second gets pointer up
2727 firstWindow->consumeMotionMove();
2728 secondWindow->consumeMotionUp();
2729
2730 // Send up event to the first window
2731 NotifyMotionArgs upMotionArgs =
2732 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2733 ADISPLAY_ID_DEFAULT);
2734 mDispatcher->notifyMotion(&upMotionArgs);
2735 // The first window gets nothing and the second gets up
2736 firstWindow->consumeMotionUp();
2737 secondWindow->assertNoEvents();
2738}
2739
Arthur Hungabbb9d82021-09-01 14:52:30 +00002740// This case will create two windows and one mirrored window on the default display and mirror
2741// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2742// the windows info of second display before default display.
2743TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2745 sp<FakeWindowHandle> firstWindowInPrimary =
2746 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2747 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002748 sp<FakeWindowHandle> secondWindowInPrimary =
2749 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2750 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002751
2752 sp<FakeWindowHandle> mirrorWindowInPrimary =
2753 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2754 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002755
2756 sp<FakeWindowHandle> firstWindowInSecondary =
2757 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2758 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002759
2760 sp<FakeWindowHandle> secondWindowInSecondary =
2761 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2762 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002763
2764 // Update window info, let it find window handle of second display first.
2765 mDispatcher->setInputWindows(
2766 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2767 {ADISPLAY_ID_DEFAULT,
2768 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2769
2770 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2771 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2772 {50, 50}))
2773 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2774
2775 // Window should receive motion event.
2776 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2777
2778 // Transfer touch focus
2779 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2780 secondWindowInPrimary->getToken()));
2781 // The first window gets cancel.
2782 firstWindowInPrimary->consumeMotionCancel();
2783 secondWindowInPrimary->consumeMotionDown();
2784
2785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2786 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2787 ADISPLAY_ID_DEFAULT, {150, 50}))
2788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2789 firstWindowInPrimary->assertNoEvents();
2790 secondWindowInPrimary->consumeMotionMove();
2791
2792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2793 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2794 {150, 50}))
2795 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2796 firstWindowInPrimary->assertNoEvents();
2797 secondWindowInPrimary->consumeMotionUp();
2798}
2799
2800// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2801// 'transferTouch' api.
2802TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2803 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2804 sp<FakeWindowHandle> firstWindowInPrimary =
2805 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2806 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002807 sp<FakeWindowHandle> secondWindowInPrimary =
2808 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2809 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002810
2811 sp<FakeWindowHandle> mirrorWindowInPrimary =
2812 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2813 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002814
2815 sp<FakeWindowHandle> firstWindowInSecondary =
2816 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2817 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002818
2819 sp<FakeWindowHandle> secondWindowInSecondary =
2820 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2821 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002822
2823 // Update window info, let it find window handle of second display first.
2824 mDispatcher->setInputWindows(
2825 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2826 {ADISPLAY_ID_DEFAULT,
2827 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2828
2829 // Touch on second display.
2830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2831 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2833
2834 // Window should receive motion event.
2835 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2836
2837 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002838 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002839
2840 // The first window gets cancel.
2841 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2842 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2843
2844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2845 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2846 SECOND_DISPLAY_ID, {150, 50}))
2847 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2848 firstWindowInPrimary->assertNoEvents();
2849 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2850
2851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2852 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2853 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2854 firstWindowInPrimary->assertNoEvents();
2855 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2856}
2857
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002858TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002859 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002860 sp<FakeWindowHandle> window =
2861 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2862
Vishnu Nair47074b82020-08-14 11:54:47 -07002863 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002865 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002866
2867 window->consumeFocusEvent(true);
2868
2869 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2870 mDispatcher->notifyKey(&keyArgs);
2871
2872 // Window should receive key down event.
2873 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2874}
2875
2876TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002877 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002878 sp<FakeWindowHandle> window =
2879 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2880
Arthur Hung72d8dc32020-03-28 00:48:39 +00002881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002882
2883 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2884 mDispatcher->notifyKey(&keyArgs);
2885 mDispatcher->waitForIdle();
2886
2887 window->assertNoEvents();
2888}
2889
2890// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2891TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002892 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002893 sp<FakeWindowHandle> window =
2894 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2895
Arthur Hung72d8dc32020-03-28 00:48:39 +00002896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002897
2898 // Send key
2899 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2900 mDispatcher->notifyKey(&keyArgs);
2901 // Send motion
2902 NotifyMotionArgs motionArgs =
2903 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2904 ADISPLAY_ID_DEFAULT);
2905 mDispatcher->notifyMotion(&motionArgs);
2906
2907 // Window should receive only the motion event
2908 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2909 window->assertNoEvents(); // Key event or focus event will not be received
2910}
2911
arthurhungea3f4fc2020-12-21 23:18:53 +08002912TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2914
arthurhungea3f4fc2020-12-21 23:18:53 +08002915 sp<FakeWindowHandle> firstWindow =
2916 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2917 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002918
arthurhungea3f4fc2020-12-21 23:18:53 +08002919 sp<FakeWindowHandle> secondWindow =
2920 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2921 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002922
2923 // Add the windows to the dispatcher
2924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2925
2926 PointF pointInFirst = {300, 200};
2927 PointF pointInSecond = {300, 600};
2928
2929 // Send down to the first window
2930 NotifyMotionArgs firstDownMotionArgs =
2931 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2932 ADISPLAY_ID_DEFAULT, {pointInFirst});
2933 mDispatcher->notifyMotion(&firstDownMotionArgs);
2934 // Only the first window should get the down event
2935 firstWindow->consumeMotionDown();
2936 secondWindow->assertNoEvents();
2937
2938 // Send down to the second window
2939 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002940 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002941 {pointInFirst, pointInSecond});
2942 mDispatcher->notifyMotion(&secondDownMotionArgs);
2943 // The first window gets a move and the second a down
2944 firstWindow->consumeMotionMove();
2945 secondWindow->consumeMotionDown();
2946
2947 // Send pointer cancel to the second window
2948 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002949 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002950 {pointInFirst, pointInSecond});
2951 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2952 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2953 // The first window gets move and the second gets cancel.
2954 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2955 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2956
2957 // Send up event.
2958 NotifyMotionArgs upMotionArgs =
2959 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2960 ADISPLAY_ID_DEFAULT);
2961 mDispatcher->notifyMotion(&upMotionArgs);
2962 // The first window gets up and the second gets nothing.
2963 firstWindow->consumeMotionUp();
2964 secondWindow->assertNoEvents();
2965}
2966
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002967TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2968 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2969
2970 sp<FakeWindowHandle> window =
2971 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2972 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2973 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2974 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2975 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2976
2977 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2978 window->assertNoEvents();
2979 mDispatcher->waitForIdle();
2980}
2981
chaviwd1c23182019-12-20 18:44:56 -08002982class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002983public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002984 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002985 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002986 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002987 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002988 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002989 }
2990
chaviwd1c23182019-12-20 18:44:56 -08002991 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2992
2993 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2994 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2995 expectedDisplayId, expectedFlags);
2996 }
2997
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002998 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2999
3000 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3001
chaviwd1c23182019-12-20 18:44:56 -08003002 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3003 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3004 expectedDisplayId, expectedFlags);
3005 }
3006
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003007 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3008 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3009 expectedDisplayId, expectedFlags);
3010 }
3011
chaviwd1c23182019-12-20 18:44:56 -08003012 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3013 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3014 expectedDisplayId, expectedFlags);
3015 }
3016
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003017 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3018 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3019 expectedDisplayId, expectedFlags);
3020 }
3021
Arthur Hungfbfa5722021-11-16 02:45:54 +00003022 void consumeMotionPointerDown(int32_t pointerIdx) {
3023 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3024 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3025 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3026 0 /*expectedFlags*/);
3027 }
3028
Evan Rosky84f07f02021-04-16 10:42:42 -07003029 MotionEvent* consumeMotion() {
3030 InputEvent* event = mInputReceiver->consume();
3031 if (!event) {
3032 ADD_FAILURE() << "No event was produced";
3033 return nullptr;
3034 }
3035 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3036 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3037 return nullptr;
3038 }
3039 return static_cast<MotionEvent*>(event);
3040 }
3041
chaviwd1c23182019-12-20 18:44:56 -08003042 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3043
3044private:
3045 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003046};
3047
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003048using InputDispatcherMonitorTest = InputDispatcherTest;
3049
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003050/**
3051 * Two entities that receive touch: A window, and a global monitor.
3052 * The touch goes to the window, and then the window disappears.
3053 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3054 * for the monitor, as well.
3055 * 1. foregroundWindow
3056 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3057 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003058TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003059 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3060 sp<FakeWindowHandle> window =
3061 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3062
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003063 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003064
3065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3067 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3068 {100, 200}))
3069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3070
3071 // Both the foreground window and the global monitor should receive the touch down
3072 window->consumeMotionDown();
3073 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3074
3075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3076 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3077 ADISPLAY_ID_DEFAULT, {110, 200}))
3078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3079
3080 window->consumeMotionMove();
3081 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3082
3083 // Now the foreground window goes away
3084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3085 window->consumeMotionCancel();
3086 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3087
3088 // If more events come in, there will be no more foreground window to send them to. This will
3089 // cause a cancel for the monitor, as well.
3090 ASSERT_EQ(InputEventInjectionResult::FAILED,
3091 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3092 ADISPLAY_ID_DEFAULT, {120, 200}))
3093 << "Injection should fail because the window was removed";
3094 window->assertNoEvents();
3095 // Global monitor now gets the cancel
3096 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3097}
3098
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003099TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003100 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003101 sp<FakeWindowHandle> window =
3102 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003104
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003105 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003106
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003108 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003110 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003111 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003112}
3113
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003114TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3115 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003116
Chris Yea209fde2020-07-22 13:54:51 -07003117 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003118 sp<FakeWindowHandle> window =
3119 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003121
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003123 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003124 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003125 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003126 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003127
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003128 // Pilfer pointers from the monitor.
3129 // This should not do anything and the window should continue to receive events.
3130 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003131
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003133 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3134 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003135 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003136
3137 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3138 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003139}
3140
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003141TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003142 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3143 sp<FakeWindowHandle> window =
3144 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3146 window->setWindowOffset(20, 40);
3147 window->setWindowTransform(0, 1, -1, 0);
3148
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003149 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003150
3151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3152 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3153 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3154 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3155 MotionEvent* event = monitor.consumeMotion();
3156 // Even though window has transform, gesture monitor must not.
3157 ASSERT_EQ(ui::Transform(), event->getTransform());
3158}
3159
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003160TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003162 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003163
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003164 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003165 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003166 << "Injection should fail if there is a monitor, but no touchable window";
3167 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003168}
3169
chaviw81e2bb92019-12-18 15:03:51 -08003170TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003171 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003172 sp<FakeWindowHandle> window =
3173 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3174
Arthur Hung72d8dc32020-03-28 00:48:39 +00003175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003176
3177 NotifyMotionArgs motionArgs =
3178 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3179 ADISPLAY_ID_DEFAULT);
3180
3181 mDispatcher->notifyMotion(&motionArgs);
3182 // Window should receive motion down event.
3183 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3184
3185 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003186 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003187 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3188 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3189 motionArgs.pointerCoords[0].getX() - 10);
3190
3191 mDispatcher->notifyMotion(&motionArgs);
3192 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3193 0 /*expectedFlags*/);
3194}
3195
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003196/**
3197 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3198 * the device default right away. In the test scenario, we check both the default value,
3199 * and the action of enabling / disabling.
3200 */
3201TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003202 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003203 sp<FakeWindowHandle> window =
3204 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003205 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003206
3207 // Set focused application.
3208 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003209 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003210
3211 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003213 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003214 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3215
3216 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003217 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003219 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3220
3221 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003222 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3223 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003224 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003225 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003227 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003228 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3229
3230 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003231 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003233 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3234
3235 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003236 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3237 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003238 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003239 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003241 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003242 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3243
3244 window->assertNoEvents();
3245}
3246
Gang Wange9087892020-01-07 12:17:14 -05003247TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003249 sp<FakeWindowHandle> window =
3250 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3251
3252 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003253 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003254
Arthur Hung72d8dc32020-03-28 00:48:39 +00003255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003256 setFocusedWindow(window);
3257
Gang Wange9087892020-01-07 12:17:14 -05003258 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3259
3260 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3261 mDispatcher->notifyKey(&keyArgs);
3262
3263 InputEvent* event = window->consume();
3264 ASSERT_NE(event, nullptr);
3265
3266 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3267 ASSERT_NE(verified, nullptr);
3268 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3269
3270 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3271 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3272 ASSERT_EQ(keyArgs.source, verified->source);
3273 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3274
3275 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3276
3277 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003278 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003279 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003280 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3281 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3282 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3283 ASSERT_EQ(0, verifiedKey.repeatCount);
3284}
3285
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003286TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003287 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003288 sp<FakeWindowHandle> window =
3289 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3290
3291 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3292
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003293 ui::Transform transform;
3294 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3295
3296 gui::DisplayInfo displayInfo;
3297 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3298 displayInfo.transform = transform;
3299
3300 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003301
3302 NotifyMotionArgs motionArgs =
3303 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3304 ADISPLAY_ID_DEFAULT);
3305 mDispatcher->notifyMotion(&motionArgs);
3306
3307 InputEvent* event = window->consume();
3308 ASSERT_NE(event, nullptr);
3309
3310 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3311 ASSERT_NE(verified, nullptr);
3312 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3313
3314 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3315 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3316 EXPECT_EQ(motionArgs.source, verified->source);
3317 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3318
3319 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3320
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003321 const vec2 rawXY =
3322 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3323 motionArgs.pointerCoords[0].getXYValue());
3324 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3325 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003326 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003327 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003328 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003329 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3330 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3331}
3332
chaviw09c8d2d2020-08-24 15:48:26 -07003333/**
3334 * Ensure that separate calls to sign the same data are generating the same key.
3335 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3336 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3337 * tests.
3338 */
3339TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3340 KeyEvent event = getTestKeyEvent();
3341 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3342
3343 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3344 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3345 ASSERT_EQ(hmac1, hmac2);
3346}
3347
3348/**
3349 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3350 */
3351TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3352 KeyEvent event = getTestKeyEvent();
3353 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3354 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3355
3356 verifiedEvent.deviceId += 1;
3357 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3358
3359 verifiedEvent.source += 1;
3360 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3361
3362 verifiedEvent.eventTimeNanos += 1;
3363 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3364
3365 verifiedEvent.displayId += 1;
3366 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3367
3368 verifiedEvent.action += 1;
3369 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3370
3371 verifiedEvent.downTimeNanos += 1;
3372 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3373
3374 verifiedEvent.flags += 1;
3375 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3376
3377 verifiedEvent.keyCode += 1;
3378 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3379
3380 verifiedEvent.scanCode += 1;
3381 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3382
3383 verifiedEvent.metaState += 1;
3384 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3385
3386 verifiedEvent.repeatCount += 1;
3387 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3388}
3389
Vishnu Nair958da932020-08-21 17:12:37 -07003390TEST_F(InputDispatcherTest, SetFocusedWindow) {
3391 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3392 sp<FakeWindowHandle> windowTop =
3393 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3394 sp<FakeWindowHandle> windowSecond =
3395 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3396 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3397
3398 // Top window is also focusable but is not granted focus.
3399 windowTop->setFocusable(true);
3400 windowSecond->setFocusable(true);
3401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3402 setFocusedWindow(windowSecond);
3403
3404 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3406 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003407
3408 // Focused window should receive event.
3409 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3410 windowTop->assertNoEvents();
3411}
3412
3413TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3415 sp<FakeWindowHandle> window =
3416 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3417 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3418
3419 window->setFocusable(true);
3420 // Release channel for window is no longer valid.
3421 window->releaseChannel();
3422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3423 setFocusedWindow(window);
3424
3425 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003426 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3427 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003428
3429 // window channel is invalid, so it should not receive any input event.
3430 window->assertNoEvents();
3431}
3432
3433TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3434 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3435 sp<FakeWindowHandle> window =
3436 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003437 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003438 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3439
Vishnu Nair958da932020-08-21 17:12:37 -07003440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3441 setFocusedWindow(window);
3442
3443 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003444 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3445 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003446
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003447 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003448 window->assertNoEvents();
3449}
3450
3451TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3452 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3453 sp<FakeWindowHandle> windowTop =
3454 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3455 sp<FakeWindowHandle> windowSecond =
3456 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3457 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3458
3459 windowTop->setFocusable(true);
3460 windowSecond->setFocusable(true);
3461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3462 setFocusedWindow(windowTop);
3463 windowTop->consumeFocusEvent(true);
3464
3465 setFocusedWindow(windowSecond, windowTop);
3466 windowSecond->consumeFocusEvent(true);
3467 windowTop->consumeFocusEvent(false);
3468
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3470 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003471
3472 // Focused window should receive event.
3473 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3474}
3475
3476TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3477 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3478 sp<FakeWindowHandle> windowTop =
3479 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3480 sp<FakeWindowHandle> windowSecond =
3481 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3482 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3483
3484 windowTop->setFocusable(true);
3485 windowSecond->setFocusable(true);
3486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3487 setFocusedWindow(windowSecond, windowTop);
3488
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003489 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3490 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003491
3492 // Event should be dropped.
3493 windowTop->assertNoEvents();
3494 windowSecond->assertNoEvents();
3495}
3496
3497TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3498 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3499 sp<FakeWindowHandle> window =
3500 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3501 sp<FakeWindowHandle> previousFocusedWindow =
3502 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3503 ADISPLAY_ID_DEFAULT);
3504 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3505
3506 window->setFocusable(true);
3507 previousFocusedWindow->setFocusable(true);
3508 window->setVisible(false);
3509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3510 setFocusedWindow(previousFocusedWindow);
3511 previousFocusedWindow->consumeFocusEvent(true);
3512
3513 // Requesting focus on invisible window takes focus from currently focused window.
3514 setFocusedWindow(window);
3515 previousFocusedWindow->consumeFocusEvent(false);
3516
3517 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003519 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003520 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003521
3522 // Window does not get focus event or key down.
3523 window->assertNoEvents();
3524
3525 // Window becomes visible.
3526 window->setVisible(true);
3527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3528
3529 // Window receives focus event.
3530 window->consumeFocusEvent(true);
3531 // Focused window receives key down.
3532 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3533}
3534
Vishnu Nair599f1412021-06-21 10:39:58 -07003535TEST_F(InputDispatcherTest, DisplayRemoved) {
3536 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3537 sp<FakeWindowHandle> window =
3538 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3539 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3540
3541 // window is granted focus.
3542 window->setFocusable(true);
3543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3544 setFocusedWindow(window);
3545 window->consumeFocusEvent(true);
3546
3547 // When a display is removed window loses focus.
3548 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3549 window->consumeFocusEvent(false);
3550}
3551
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003552/**
3553 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3554 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3555 * of the 'slipperyEnterWindow'.
3556 *
3557 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3558 * a way so that the touched location is no longer covered by the top window.
3559 *
3560 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3561 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3562 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3563 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3564 * with ACTION_DOWN).
3565 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3566 * window moved itself away from the touched location and had Flag::SLIPPERY.
3567 *
3568 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3569 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3570 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3571 *
3572 * In this test, we ensure that the event received by the bottom window has
3573 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3574 */
3575TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003576 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3577 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003578
3579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3580 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3581
3582 sp<FakeWindowHandle> slipperyExitWindow =
3583 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003584 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003585 // Make sure this one overlaps the bottom window
3586 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3587 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3588 // one. Windows with the same owner are not considered to be occluding each other.
3589 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3590
3591 sp<FakeWindowHandle> slipperyEnterWindow =
3592 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3593 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3594
3595 mDispatcher->setInputWindows(
3596 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3597
3598 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3599 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3600 ADISPLAY_ID_DEFAULT, {{50, 50}});
3601 mDispatcher->notifyMotion(&args);
3602 slipperyExitWindow->consumeMotionDown();
3603 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3604 mDispatcher->setInputWindows(
3605 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3606
3607 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3608 ADISPLAY_ID_DEFAULT, {{51, 51}});
3609 mDispatcher->notifyMotion(&args);
3610
3611 slipperyExitWindow->consumeMotionCancel();
3612
3613 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3614 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3615}
3616
Garfield Tan1c7bc862020-01-28 13:24:04 -08003617class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3618protected:
3619 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3620 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3621
Chris Yea209fde2020-07-22 13:54:51 -07003622 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003623 sp<FakeWindowHandle> mWindow;
3624
3625 virtual void SetUp() override {
3626 mFakePolicy = new FakeInputDispatcherPolicy();
3627 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003628 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003629 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3630 ASSERT_EQ(OK, mDispatcher->start());
3631
3632 setUpWindow();
3633 }
3634
3635 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003636 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003637 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3638
Vishnu Nair47074b82020-08-14 11:54:47 -07003639 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003641 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003642 mWindow->consumeFocusEvent(true);
3643 }
3644
Chris Ye2ad95392020-09-01 13:44:44 -07003645 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003646 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003647 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003648 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3649 mDispatcher->notifyKey(&keyArgs);
3650
3651 // Window should receive key down event.
3652 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3653 }
3654
3655 void expectKeyRepeatOnce(int32_t repeatCount) {
3656 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3657 InputEvent* repeatEvent = mWindow->consume();
3658 ASSERT_NE(nullptr, repeatEvent);
3659
3660 uint32_t eventType = repeatEvent->getType();
3661 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3662
3663 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3664 uint32_t eventAction = repeatKeyEvent->getAction();
3665 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3666 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3667 }
3668
Chris Ye2ad95392020-09-01 13:44:44 -07003669 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003670 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003671 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003672 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3673 mDispatcher->notifyKey(&keyArgs);
3674
3675 // Window should receive key down event.
3676 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3677 0 /*expectedFlags*/);
3678 }
3679};
3680
3681TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003682 sendAndConsumeKeyDown(1 /* deviceId */);
3683 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3684 expectKeyRepeatOnce(repeatCount);
3685 }
3686}
3687
3688TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3689 sendAndConsumeKeyDown(1 /* deviceId */);
3690 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3691 expectKeyRepeatOnce(repeatCount);
3692 }
3693 sendAndConsumeKeyDown(2 /* deviceId */);
3694 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003695 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3696 expectKeyRepeatOnce(repeatCount);
3697 }
3698}
3699
3700TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003701 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003702 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003703 sendAndConsumeKeyUp(1 /* deviceId */);
3704 mWindow->assertNoEvents();
3705}
3706
3707TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3708 sendAndConsumeKeyDown(1 /* deviceId */);
3709 expectKeyRepeatOnce(1 /*repeatCount*/);
3710 sendAndConsumeKeyDown(2 /* deviceId */);
3711 expectKeyRepeatOnce(1 /*repeatCount*/);
3712 // Stale key up from device 1.
3713 sendAndConsumeKeyUp(1 /* deviceId */);
3714 // Device 2 is still down, keep repeating
3715 expectKeyRepeatOnce(2 /*repeatCount*/);
3716 expectKeyRepeatOnce(3 /*repeatCount*/);
3717 // Device 2 key up
3718 sendAndConsumeKeyUp(2 /* deviceId */);
3719 mWindow->assertNoEvents();
3720}
3721
3722TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3723 sendAndConsumeKeyDown(1 /* deviceId */);
3724 expectKeyRepeatOnce(1 /*repeatCount*/);
3725 sendAndConsumeKeyDown(2 /* deviceId */);
3726 expectKeyRepeatOnce(1 /*repeatCount*/);
3727 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3728 sendAndConsumeKeyUp(2 /* deviceId */);
3729 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003730 mWindow->assertNoEvents();
3731}
3732
liushenxiang42232912021-05-21 20:24:09 +08003733TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3734 sendAndConsumeKeyDown(DEVICE_ID);
3735 expectKeyRepeatOnce(1 /*repeatCount*/);
3736 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3737 mDispatcher->notifyDeviceReset(&args);
3738 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3739 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3740 mWindow->assertNoEvents();
3741}
3742
Garfield Tan1c7bc862020-01-28 13:24:04 -08003743TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003744 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003745 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3746 InputEvent* repeatEvent = mWindow->consume();
3747 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3748 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3749 IdGenerator::getSource(repeatEvent->getId()));
3750 }
3751}
3752
3753TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003754 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003755
3756 std::unordered_set<int32_t> idSet;
3757 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3758 InputEvent* repeatEvent = mWindow->consume();
3759 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3760 int32_t id = repeatEvent->getId();
3761 EXPECT_EQ(idSet.end(), idSet.find(id));
3762 idSet.insert(id);
3763 }
3764}
3765
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003766/* Test InputDispatcher for MultiDisplay */
3767class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3768public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003769 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003770 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003771
Chris Yea209fde2020-07-22 13:54:51 -07003772 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003773 windowInPrimary =
3774 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003775
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003776 // Set focus window for primary display, but focused display would be second one.
3777 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003778 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003780 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003781 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003782
Chris Yea209fde2020-07-22 13:54:51 -07003783 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003784 windowInSecondary =
3785 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003786 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003787 // Set focus display to second one.
3788 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3789 // Set focus window for second display.
3790 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003791 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003792 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003793 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003794 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003795 }
3796
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003797 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003798 InputDispatcherTest::TearDown();
3799
Chris Yea209fde2020-07-22 13:54:51 -07003800 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003801 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003802 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003803 windowInSecondary.clear();
3804 }
3805
3806protected:
Chris Yea209fde2020-07-22 13:54:51 -07003807 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003808 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003809 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003810 sp<FakeWindowHandle> windowInSecondary;
3811};
3812
3813TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3814 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3816 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3817 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003818 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003819 windowInSecondary->assertNoEvents();
3820
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003821 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3823 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003825 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003826 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003827}
3828
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003829TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003830 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3832 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003833 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003834 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003835 windowInSecondary->assertNoEvents();
3836
3837 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003839 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003840 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003841 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003842
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003843 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003844 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003845
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003846 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003847 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3848 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003849
3850 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003851 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003852 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003853 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003854 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003855 windowInSecondary->assertNoEvents();
3856}
3857
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003858// Test per-display input monitors for motion event.
3859TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003860 FakeMonitorReceiver monitorInPrimary =
3861 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3862 FakeMonitorReceiver monitorInSecondary =
3863 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003864
3865 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003869 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003870 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003871 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003872 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003873
3874 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3876 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3877 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003878 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003879 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003880 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003881 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003882
3883 // Test inject a non-pointer motion event.
3884 // If specific a display, it will dispatch to the focused window of particular display,
3885 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3887 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3888 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003889 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003890 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003891 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003892 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003893}
3894
3895// Test per-display input monitors for key event.
3896TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003897 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003898 FakeMonitorReceiver monitorInPrimary =
3899 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3900 FakeMonitorReceiver monitorInSecondary =
3901 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003902
3903 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3905 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003906 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003907 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003908 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003909 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003910}
3911
Vishnu Nair958da932020-08-21 17:12:37 -07003912TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3913 sp<FakeWindowHandle> secondWindowInPrimary =
3914 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3915 secondWindowInPrimary->setFocusable(true);
3916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3917 setFocusedWindow(secondWindowInPrimary);
3918 windowInPrimary->consumeFocusEvent(false);
3919 secondWindowInPrimary->consumeFocusEvent(true);
3920
3921 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3923 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003924 windowInPrimary->assertNoEvents();
3925 windowInSecondary->assertNoEvents();
3926 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3927}
3928
Arthur Hungdfd528e2021-12-08 13:23:04 +00003929TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3930 FakeMonitorReceiver monitorInPrimary =
3931 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3932 FakeMonitorReceiver monitorInSecondary =
3933 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3934
3935 // Test touch down on primary display.
3936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3937 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3939 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3940 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3941
3942 // Test touch down on second display.
3943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3944 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3946 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3947 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3948
3949 // Trigger cancel touch.
3950 mDispatcher->cancelCurrentTouch();
3951 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3952 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3953 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3954 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3955
3956 // Test inject a move motion event, no window/monitor should receive the event.
3957 ASSERT_EQ(InputEventInjectionResult::FAILED,
3958 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3959 ADISPLAY_ID_DEFAULT, {110, 200}))
3960 << "Inject motion event should return InputEventInjectionResult::FAILED";
3961 windowInPrimary->assertNoEvents();
3962 monitorInPrimary.assertNoEvents();
3963
3964 ASSERT_EQ(InputEventInjectionResult::FAILED,
3965 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3966 SECOND_DISPLAY_ID, {110, 200}))
3967 << "Inject motion event should return InputEventInjectionResult::FAILED";
3968 windowInSecondary->assertNoEvents();
3969 monitorInSecondary.assertNoEvents();
3970}
3971
Jackal Guof9696682018-10-05 12:23:23 +08003972class InputFilterTest : public InputDispatcherTest {
3973protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003974 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3975 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003976 NotifyMotionArgs motionArgs;
3977
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003978 motionArgs =
3979 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003980 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003981 motionArgs =
3982 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003983 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003984 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003985 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003986 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3987 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003988 } else {
3989 mFakePolicy->assertFilterInputEventWasNotCalled();
3990 }
3991 }
3992
3993 void testNotifyKey(bool expectToBeFiltered) {
3994 NotifyKeyArgs keyArgs;
3995
3996 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3997 mDispatcher->notifyKey(&keyArgs);
3998 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3999 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004000 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004001
4002 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004003 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004004 } else {
4005 mFakePolicy->assertFilterInputEventWasNotCalled();
4006 }
4007 }
4008};
4009
4010// Test InputFilter for MotionEvent
4011TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4012 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4013 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4014 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4015
4016 // Enable InputFilter
4017 mDispatcher->setInputFilterEnabled(true);
4018 // Test touch on both primary and second display, and check if both events are filtered.
4019 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4020 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4021
4022 // Disable InputFilter
4023 mDispatcher->setInputFilterEnabled(false);
4024 // Test touch on both primary and second display, and check if both events aren't filtered.
4025 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4026 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4027}
4028
4029// Test InputFilter for KeyEvent
4030TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4031 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4032 testNotifyKey(/*expectToBeFiltered*/ false);
4033
4034 // Enable InputFilter
4035 mDispatcher->setInputFilterEnabled(true);
4036 // Send a key event, and check if it is filtered.
4037 testNotifyKey(/*expectToBeFiltered*/ true);
4038
4039 // Disable InputFilter
4040 mDispatcher->setInputFilterEnabled(false);
4041 // Send a key event, and check if it isn't filtered.
4042 testNotifyKey(/*expectToBeFiltered*/ false);
4043}
4044
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004045// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4046// logical display coordinate space.
4047TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4048 ui::Transform firstDisplayTransform;
4049 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4050 ui::Transform secondDisplayTransform;
4051 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4052
4053 std::vector<gui::DisplayInfo> displayInfos(2);
4054 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4055 displayInfos[0].transform = firstDisplayTransform;
4056 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4057 displayInfos[1].transform = secondDisplayTransform;
4058
4059 mDispatcher->onWindowInfosChanged({}, displayInfos);
4060
4061 // Enable InputFilter
4062 mDispatcher->setInputFilterEnabled(true);
4063
4064 // Ensure the correct transforms are used for the displays.
4065 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4066 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4067}
4068
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004069class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4070protected:
4071 virtual void SetUp() override {
4072 InputDispatcherTest::SetUp();
4073
4074 /**
4075 * We don't need to enable input filter to test the injected event policy, but we enabled it
4076 * here to make the tests more realistic, since this policy only matters when inputfilter is
4077 * on.
4078 */
4079 mDispatcher->setInputFilterEnabled(true);
4080
4081 std::shared_ptr<InputApplicationHandle> application =
4082 std::make_shared<FakeApplicationHandle>();
4083 mWindow =
4084 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4085
4086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4087 mWindow->setFocusable(true);
4088 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4089 setFocusedWindow(mWindow);
4090 mWindow->consumeFocusEvent(true);
4091 }
4092
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004093 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4094 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004095 KeyEvent event;
4096
4097 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4098 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4099 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4100 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4101 const int32_t additionalPolicyFlags =
4102 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004104 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004105 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4106 policyFlags | additionalPolicyFlags));
4107
4108 InputEvent* received = mWindow->consume();
4109 ASSERT_NE(nullptr, received);
4110 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004111 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4112 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4113 ASSERT_EQ(flags, keyEvent.getFlags());
4114 }
4115
4116 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4117 int32_t flags) {
4118 MotionEvent event;
4119 PointerProperties pointerProperties[1];
4120 PointerCoords pointerCoords[1];
4121 pointerProperties[0].clear();
4122 pointerProperties[0].id = 0;
4123 pointerCoords[0].clear();
4124 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4125 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4126
4127 ui::Transform identityTransform;
4128 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4129 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4130 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4131 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4132 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004133 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004134 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004135 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4136
4137 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004139 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004140 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4141 policyFlags | additionalPolicyFlags));
4142
4143 InputEvent* received = mWindow->consume();
4144 ASSERT_NE(nullptr, received);
4145 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4146 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4147 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4148 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004149 }
4150
4151private:
4152 sp<FakeWindowHandle> mWindow;
4153};
4154
4155TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004156 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4157 // filter. Without it, the event will no different from a regularly injected event, and the
4158 // injected device id will be overwritten.
4159 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4160 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004161}
4162
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004163TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004164 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004165 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4166 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4167}
4168
4169TEST_F(InputFilterInjectionPolicyTest,
4170 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4171 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4172 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4173 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004174}
4175
4176TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4177 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004178 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179}
4180
chaviwfd6d3512019-03-25 13:23:49 -07004181class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004182 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004183 InputDispatcherTest::SetUp();
4184
Chris Yea209fde2020-07-22 13:54:51 -07004185 std::shared_ptr<FakeApplicationHandle> application =
4186 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004187 mUnfocusedWindow =
4188 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004189 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004190
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004191 mFocusedWindow =
4192 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4193 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004194
4195 // Set focused application.
4196 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004197 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004198
4199 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004201 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004202 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004203 }
4204
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004205 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004206 InputDispatcherTest::TearDown();
4207
4208 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004209 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004210 }
4211
4212protected:
4213 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004214 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004215 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004216};
4217
4218// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4219// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4220// the onPointerDownOutsideFocus callback.
4221TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004223 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4224 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004225 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004226 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004227
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004228 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004229 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4230}
4231
4232// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4233// DOWN on the window that doesn't have focus. Ensure no window received the
4234// onPointerDownOutsideFocus callback.
4235TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004237 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004238 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004239 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004240
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004241 ASSERT_TRUE(mDispatcher->waitForIdle());
4242 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004243}
4244
4245// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4246// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4247TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4249 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004250 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004251 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004252
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004253 ASSERT_TRUE(mDispatcher->waitForIdle());
4254 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004255}
4256
4257// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4258// DOWN on the window that already has focus. Ensure no window received the
4259// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004260TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004262 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004263 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004265 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004266
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004267 ASSERT_TRUE(mDispatcher->waitForIdle());
4268 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004269}
4270
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004271// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4272// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4273TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4274 const MotionEvent event =
4275 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4276 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4277 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4278 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4279 .build();
4280 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4281 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4282 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4283
4284 ASSERT_TRUE(mDispatcher->waitForIdle());
4285 mFakePolicy->assertOnPointerDownWasNotCalled();
4286 // Ensure that the unfocused window did not receive any FOCUS events.
4287 mUnfocusedWindow->assertNoEvents();
4288}
4289
chaviwaf87b3e2019-10-01 16:59:28 -07004290// These tests ensures we can send touch events to a single client when there are multiple input
4291// windows that point to the same client token.
4292class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4293 virtual void SetUp() override {
4294 InputDispatcherTest::SetUp();
4295
Chris Yea209fde2020-07-22 13:54:51 -07004296 std::shared_ptr<FakeApplicationHandle> application =
4297 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004298 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4299 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004300 mWindow1->setFrame(Rect(0, 0, 100, 100));
4301
4302 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4303 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004304 mWindow2->setFrame(Rect(100, 100, 200, 200));
4305
Arthur Hung72d8dc32020-03-28 00:48:39 +00004306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004307 }
4308
4309protected:
4310 sp<FakeWindowHandle> mWindow1;
4311 sp<FakeWindowHandle> mWindow2;
4312
4313 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004314 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004315 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4316 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004317 }
4318
4319 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4320 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004321 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004322 InputEvent* event = window->consume();
4323
4324 ASSERT_NE(nullptr, event) << name.c_str()
4325 << ": consumer should have returned non-NULL event.";
4326
4327 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4328 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4329 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4330
4331 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004332 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004333
4334 for (size_t i = 0; i < points.size(); i++) {
4335 float expectedX = points[i].x;
4336 float expectedY = points[i].y;
4337
4338 EXPECT_EQ(expectedX, motionEvent.getX(i))
4339 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4340 << ", got " << motionEvent.getX(i);
4341 EXPECT_EQ(expectedY, motionEvent.getY(i))
4342 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4343 << ", got " << motionEvent.getY(i);
4344 }
4345 }
chaviw9eaa22c2020-07-01 16:21:27 -07004346
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004347 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004348 std::vector<PointF> expectedPoints) {
4349 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4350 ADISPLAY_ID_DEFAULT, touchedPoints);
4351 mDispatcher->notifyMotion(&motionArgs);
4352
4353 // Always consume from window1 since it's the window that has the InputReceiver
4354 consumeMotionEvent(mWindow1, action, expectedPoints);
4355 }
chaviwaf87b3e2019-10-01 16:59:28 -07004356};
4357
4358TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4359 // Touch Window 1
4360 PointF touchedPoint = {10, 10};
4361 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004362 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004363
4364 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004365 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004366
4367 // Touch Window 2
4368 touchedPoint = {150, 150};
4369 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004370 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004371}
4372
chaviw9eaa22c2020-07-01 16:21:27 -07004373TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4374 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004375 mWindow2->setWindowScale(0.5f, 0.5f);
4376
4377 // Touch Window 1
4378 PointF touchedPoint = {10, 10};
4379 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004380 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004381 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004382 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004383
4384 // Touch Window 2
4385 touchedPoint = {150, 150};
4386 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004387 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4388 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004389
chaviw9eaa22c2020-07-01 16:21:27 -07004390 // Update the transform so rotation is set
4391 mWindow2->setWindowTransform(0, -1, 1, 0);
4392 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4393 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004394}
4395
chaviw9eaa22c2020-07-01 16:21:27 -07004396TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004397 mWindow2->setWindowScale(0.5f, 0.5f);
4398
4399 // Touch Window 1
4400 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4401 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004402 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004403
4404 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004405 touchedPoints.push_back(PointF{150, 150});
4406 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004407 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004408
chaviw9eaa22c2020-07-01 16:21:27 -07004409 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004410 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004411 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004412
chaviw9eaa22c2020-07-01 16:21:27 -07004413 // Update the transform so rotation is set for Window 2
4414 mWindow2->setWindowTransform(0, -1, 1, 0);
4415 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004416 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004417}
4418
chaviw9eaa22c2020-07-01 16:21:27 -07004419TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004420 mWindow2->setWindowScale(0.5f, 0.5f);
4421
4422 // Touch Window 1
4423 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4424 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004425 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004426
4427 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004428 touchedPoints.push_back(PointF{150, 150});
4429 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004430
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004431 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004432
4433 // Move both windows
4434 touchedPoints = {{20, 20}, {175, 175}};
4435 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4436 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4437
chaviw9eaa22c2020-07-01 16:21:27 -07004438 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004439
chaviw9eaa22c2020-07-01 16:21:27 -07004440 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004441 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004442 expectedPoints.pop_back();
4443
4444 // Touch Window 2
4445 mWindow2->setWindowTransform(0, -1, 1, 0);
4446 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004447 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004448
4449 // Move both windows
4450 touchedPoints = {{20, 20}, {175, 175}};
4451 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4452 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4453
4454 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004455}
4456
4457TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4458 mWindow1->setWindowScale(0.5f, 0.5f);
4459
4460 // Touch Window 1
4461 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4462 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004463 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004464
4465 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004466 touchedPoints.push_back(PointF{150, 150});
4467 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004468
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004469 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004470
4471 // Move both windows
4472 touchedPoints = {{20, 20}, {175, 175}};
4473 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4474 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4475
chaviw9eaa22c2020-07-01 16:21:27 -07004476 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004477}
4478
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004479class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4480 virtual void SetUp() override {
4481 InputDispatcherTest::SetUp();
4482
Chris Yea209fde2020-07-22 13:54:51 -07004483 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004484 mApplication->setDispatchingTimeout(20ms);
4485 mWindow =
4486 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4487 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004488 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004489 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004490
4491 // Set focused application.
4492 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4493
4494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004495 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004496 mWindow->consumeFocusEvent(true);
4497 }
4498
4499 virtual void TearDown() override {
4500 InputDispatcherTest::TearDown();
4501 mWindow.clear();
4502 }
4503
4504protected:
Chris Yea209fde2020-07-22 13:54:51 -07004505 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004506 sp<FakeWindowHandle> mWindow;
4507 static constexpr PointF WINDOW_LOCATION = {20, 20};
4508
4509 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004511 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4512 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4515 WINDOW_LOCATION));
4516 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004517
4518 sp<FakeWindowHandle> addSpyWindow() {
4519 sp<FakeWindowHandle> spy =
4520 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4521 spy->setTrustedOverlay(true);
4522 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004523 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004524 spy->setDispatchingTimeout(30ms);
4525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4526 return spy;
4527 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004528};
4529
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004530// Send a tap and respond, which should not cause an ANR.
4531TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4532 tapOnWindow();
4533 mWindow->consumeMotionDown();
4534 mWindow->consumeMotionUp();
4535 ASSERT_TRUE(mDispatcher->waitForIdle());
4536 mFakePolicy->assertNotifyAnrWasNotCalled();
4537}
4538
4539// Send a regular key and respond, which should not cause an ANR.
4540TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4543 ASSERT_TRUE(mDispatcher->waitForIdle());
4544 mFakePolicy->assertNotifyAnrWasNotCalled();
4545}
4546
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004547TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4548 mWindow->setFocusable(false);
4549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4550 mWindow->consumeFocusEvent(false);
4551
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004552 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004553 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004554 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4555 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004557 // Key will not go to window because we have no focused window.
4558 // The 'no focused window' ANR timer should start instead.
4559
4560 // Now, the focused application goes away.
4561 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4562 // The key should get dropped and there should be no ANR.
4563
4564 ASSERT_TRUE(mDispatcher->waitForIdle());
4565 mFakePolicy->assertNotifyAnrWasNotCalled();
4566}
4567
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004568// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4570// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004571TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004572 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004573 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4574 WINDOW_LOCATION));
4575
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004576 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4577 ASSERT_TRUE(sequenceNum);
4578 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004579 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 mWindow->finishEvent(*sequenceNum);
4582 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4583 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004584 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004585 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004586}
4587
4588// Send a key to the app and have the app not respond right away.
4589TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4590 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004592 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4593 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004594 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004595 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004596 ASSERT_TRUE(mDispatcher->waitForIdle());
4597}
4598
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004599// We have a focused application, but no focused window
4600TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004601 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4603 mWindow->consumeFocusEvent(false);
4604
4605 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4608 WINDOW_LOCATION));
4609 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4610 mDispatcher->waitForIdle();
4611 mFakePolicy->assertNotifyAnrWasNotCalled();
4612
4613 // Once a focused event arrives, we get an ANR for this application
4614 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4615 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004616 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004618 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004619 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004621 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 ASSERT_TRUE(mDispatcher->waitForIdle());
4623}
4624
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004625/**
4626 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4627 * there will not be an ANR.
4628 */
4629TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4630 mWindow->setFocusable(false);
4631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4632 mWindow->consumeFocusEvent(false);
4633
4634 KeyEvent event;
4635 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4636 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4637
4638 // Define a valid key down event that is stale (too old).
4639 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4640 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4641 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4642
4643 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4644
4645 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004646 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004647 InputEventInjectionSync::WAIT_FOR_RESULT,
4648 INJECT_EVENT_TIMEOUT, policyFlags);
4649 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4650 << "Injection should fail because the event is stale";
4651
4652 ASSERT_TRUE(mDispatcher->waitForIdle());
4653 mFakePolicy->assertNotifyAnrWasNotCalled();
4654 mWindow->assertNoEvents();
4655}
4656
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004658// Make sure that we don't notify policy twice about the same ANR.
4659TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004660 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4662 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663
4664 // Once a focused event arrives, we get an ANR for this application
4665 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4666 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004667 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004669 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004670 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004671 const std::chrono::duration appTimeout =
4672 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004673 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004675 std::this_thread::sleep_for(appTimeout);
4676 // ANR should not be raised again. It is up to policy to do that if it desires.
4677 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004678
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004679 // If we now get a focused window, the ANR should stop, but the policy handles that via
4680 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681 ASSERT_TRUE(mDispatcher->waitForIdle());
4682}
4683
4684// We have a focused application, but no focused window
4685TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004686 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4688 mWindow->consumeFocusEvent(false);
4689
4690 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4694 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695
4696 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004697 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698
4699 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004700 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004701 ASSERT_TRUE(mDispatcher->waitForIdle());
4702 mWindow->assertNoEvents();
4703}
4704
4705/**
4706 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4707 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4708 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4709 * the ANR mechanism should still work.
4710 *
4711 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4712 * DOWN event, while not responding on the second one.
4713 */
4714TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4715 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4716 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4717 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4718 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4719 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004720 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721
4722 // Now send ACTION_UP, with identical timestamp
4723 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4724 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4725 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4726 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004727 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728
4729 // We have now sent down and up. Let's consume first event and then ANR on the second.
4730 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4731 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004732 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733}
4734
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004735// A spy window can receive an ANR
4736TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4737 sp<FakeWindowHandle> spy = addSpyWindow();
4738
4739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4740 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4741 WINDOW_LOCATION));
4742 mWindow->consumeMotionDown();
4743
4744 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4745 ASSERT_TRUE(sequenceNum);
4746 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004747 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004748
4749 spy->finishEvent(*sequenceNum);
4750 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4751 0 /*flags*/);
4752 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004753 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004754}
4755
4756// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004758TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4759 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004761 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4762 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004763 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765
4766 // Stuck on the ACTION_UP
4767 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004768 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004769
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004770 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004771 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004772 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4773 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774
4775 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4776 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004777 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004779 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780}
4781
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004782// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004783// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004784TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4785 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786
4787 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004788 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4789 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790
4791 mWindow->consumeMotionDown();
4792 // Stuck on the ACTION_UP
4793 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004794 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004796 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004798 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4799 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800
4801 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4802 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004803 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004805 spy->assertNoEvents();
4806}
4807
4808TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4809 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4810
4811 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4812
4813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4814 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4815 WINDOW_LOCATION));
4816
4817 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4818 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4819 ASSERT_TRUE(consumeSeq);
4820
Prabir Pradhanedd96402022-02-15 01:46:16 -08004821 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004822
4823 monitor.finishEvent(*consumeSeq);
4824 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4825
4826 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004827 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828}
4829
4830// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4831// process events, you don't get an anr. When the window later becomes unresponsive again, you
4832// get an ANR again.
4833// 1. tap -> block on ACTION_UP -> receive ANR
4834// 2. consume all pending events (= queue becomes healthy again)
4835// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4836TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4837 tapOnWindow();
4838
4839 mWindow->consumeMotionDown();
4840 // Block on ACTION_UP
4841 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004842 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4844 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004845 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 mWindow->assertNoEvents();
4847
4848 tapOnWindow();
4849 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004850 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004851 mWindow->consumeMotionUp();
4852
4853 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004854 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004855 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 mWindow->assertNoEvents();
4857}
4858
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004859// If a connection remains unresponsive for a while, make sure policy is only notified once about
4860// it.
4861TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4864 WINDOW_LOCATION));
4865
4866 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004867 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004869 // 'notifyConnectionUnresponsive' should only be called once per connection
4870 mFakePolicy->assertNotifyAnrWasNotCalled();
4871 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 mWindow->consumeMotionDown();
4873 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4874 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4875 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004876 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004877 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004878 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879}
4880
4881/**
4882 * If a window is processing a motion event, and then a key event comes in, the key event should
4883 * not to to the focused window until the motion is processed.
4884 *
4885 * Warning!!!
4886 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4887 * and the injection timeout that we specify when injecting the key.
4888 * We must have the injection timeout (10ms) be smaller than
4889 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4890 *
4891 * If that value changes, this test should also change.
4892 */
4893TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4894 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4896
4897 tapOnWindow();
4898 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4899 ASSERT_TRUE(downSequenceNum);
4900 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4901 ASSERT_TRUE(upSequenceNum);
4902 // Don't finish the events yet, and send a key
4903 // Injection will "succeed" because we will eventually give up and send the key to the focused
4904 // window even if motions are still being processed. But because the injection timeout is short,
4905 // we will receive INJECTION_TIMED_OUT as the result.
4906
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004907 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004908 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004909 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4910 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911 // Key will not be sent to the window, yet, because the window is still processing events
4912 // and the key remains pending, waiting for the touch events to be processed
4913 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4914 ASSERT_FALSE(keySequenceNum);
4915
4916 std::this_thread::sleep_for(500ms);
4917 // if we wait long enough though, dispatcher will give up, and still send the key
4918 // to the focused window, even though we have not yet finished the motion event
4919 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4920 mWindow->finishEvent(*downSequenceNum);
4921 mWindow->finishEvent(*upSequenceNum);
4922}
4923
4924/**
4925 * If a window is processing a motion event, and then a key event comes in, the key event should
4926 * not go to the focused window until the motion is processed.
4927 * If then a new motion comes in, then the pending key event should be going to the currently
4928 * focused window right away.
4929 */
4930TEST_F(InputDispatcherSingleWindowAnr,
4931 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4932 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4934
4935 tapOnWindow();
4936 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4937 ASSERT_TRUE(downSequenceNum);
4938 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4939 ASSERT_TRUE(upSequenceNum);
4940 // Don't finish the events yet, and send a key
4941 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004943 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004944 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945 // At this point, key is still pending, and should not be sent to the application yet.
4946 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4947 ASSERT_FALSE(keySequenceNum);
4948
4949 // Now tap down again. It should cause the pending key to go to the focused window right away.
4950 tapOnWindow();
4951 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4952 // the other events yet. We can finish events in any order.
4953 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4954 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4955 mWindow->consumeMotionDown();
4956 mWindow->consumeMotionUp();
4957 mWindow->assertNoEvents();
4958}
4959
4960class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4961 virtual void SetUp() override {
4962 InputDispatcherTest::SetUp();
4963
Chris Yea209fde2020-07-22 13:54:51 -07004964 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965 mApplication->setDispatchingTimeout(10ms);
4966 mUnfocusedWindow =
4967 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4968 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004969 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004970 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971
4972 mFocusedWindow =
4973 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004974 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976
4977 // Set focused application.
4978 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004979 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004980
4981 // Expect one focus window exist in display.
4982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004983 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984 mFocusedWindow->consumeFocusEvent(true);
4985 }
4986
4987 virtual void TearDown() override {
4988 InputDispatcherTest::TearDown();
4989
4990 mUnfocusedWindow.clear();
4991 mFocusedWindow.clear();
4992 }
4993
4994protected:
Chris Yea209fde2020-07-22 13:54:51 -07004995 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996 sp<FakeWindowHandle> mUnfocusedWindow;
4997 sp<FakeWindowHandle> mFocusedWindow;
4998 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4999 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5000 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5001
5002 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5003
5004 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5005
5006private:
5007 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005009 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5010 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5013 location));
5014 }
5015};
5016
5017// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5018// should be ANR'd first.
5019TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005021 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5022 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005023 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024 mFocusedWindow->consumeMotionDown();
5025 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5026 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5027 // We consumed all events, so no ANR
5028 ASSERT_TRUE(mDispatcher->waitForIdle());
5029 mFakePolicy->assertNotifyAnrWasNotCalled();
5030
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005032 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5033 FOCUSED_WINDOW_LOCATION));
5034 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5035 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005036
5037 const std::chrono::duration timeout =
5038 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005039 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005040 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5041 // sequence to make it consistent
5042 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005043 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005044 mFocusedWindow->consumeMotionDown();
5045 // This cancel is generated because the connection was unresponsive
5046 mFocusedWindow->consumeMotionCancel();
5047 mFocusedWindow->assertNoEvents();
5048 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005049 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005050 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5051 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005052 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005053}
5054
5055// If we have 2 windows with identical timeouts that are both unresponsive,
5056// it doesn't matter which order they should have ANR.
5057// But we should receive ANR for both.
5058TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5059 // Set the timeout for unfocused window to match the focused window
5060 mUnfocusedWindow->setDispatchingTimeout(10ms);
5061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5062
5063 tapOnFocusedWindow();
5064 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005065 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5066 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5067 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005068
5069 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005070 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5071 mFocusedWindow->getToken() == anrConnectionToken2);
5072 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5073 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005074
5075 ASSERT_TRUE(mDispatcher->waitForIdle());
5076 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005077
5078 mFocusedWindow->consumeMotionDown();
5079 mFocusedWindow->consumeMotionUp();
5080 mUnfocusedWindow->consumeMotionOutside();
5081
Prabir Pradhanedd96402022-02-15 01:46:16 -08005082 sp<IBinder> responsiveToken1, responsiveToken2;
5083 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5084 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005085
5086 // Both applications should be marked as responsive, in any order
5087 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5088 mFocusedWindow->getToken() == responsiveToken2);
5089 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5090 mUnfocusedWindow->getToken() == responsiveToken2);
5091 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005092}
5093
5094// If a window is already not responding, the second tap on the same window should be ignored.
5095// We should also log an error to account for the dropped event (not tested here).
5096// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5097TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5098 tapOnFocusedWindow();
5099 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5100 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5101 // Receive the events, but don't respond
5102 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5103 ASSERT_TRUE(downEventSequenceNum);
5104 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5105 ASSERT_TRUE(upEventSequenceNum);
5106 const std::chrono::duration timeout =
5107 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005108 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005109
5110 // Tap once again
5111 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005112 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5114 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005115 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5117 FOCUSED_WINDOW_LOCATION));
5118 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5119 // valid touch target
5120 mUnfocusedWindow->assertNoEvents();
5121
5122 // Consume the first tap
5123 mFocusedWindow->finishEvent(*downEventSequenceNum);
5124 mFocusedWindow->finishEvent(*upEventSequenceNum);
5125 ASSERT_TRUE(mDispatcher->waitForIdle());
5126 // The second tap did not go to the focused window
5127 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005128 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005129 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5130 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 mFakePolicy->assertNotifyAnrWasNotCalled();
5132}
5133
5134// If you tap outside of all windows, there will not be ANR
5135TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005136 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005137 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5138 LOCATION_OUTSIDE_ALL_WINDOWS));
5139 ASSERT_TRUE(mDispatcher->waitForIdle());
5140 mFakePolicy->assertNotifyAnrWasNotCalled();
5141}
5142
5143// Since the focused window is paused, tapping on it should not produce any events
5144TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5145 mFocusedWindow->setPaused(true);
5146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5147
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005148 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005149 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5150 FOCUSED_WINDOW_LOCATION));
5151
5152 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5153 ASSERT_TRUE(mDispatcher->waitForIdle());
5154 // Should not ANR because the window is paused, and touches shouldn't go to it
5155 mFakePolicy->assertNotifyAnrWasNotCalled();
5156
5157 mFocusedWindow->assertNoEvents();
5158 mUnfocusedWindow->assertNoEvents();
5159}
5160
5161/**
5162 * If a window is processing a motion event, and then a key event comes in, the key event should
5163 * not to to the focused window until the motion is processed.
5164 * If a different window becomes focused at this time, the key should go to that window instead.
5165 *
5166 * Warning!!!
5167 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5168 * and the injection timeout that we specify when injecting the key.
5169 * We must have the injection timeout (10ms) be smaller than
5170 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5171 *
5172 * If that value changes, this test should also change.
5173 */
5174TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5175 // Set a long ANR timeout to prevent it from triggering
5176 mFocusedWindow->setDispatchingTimeout(2s);
5177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5178
5179 tapOnUnfocusedWindow();
5180 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5181 ASSERT_TRUE(downSequenceNum);
5182 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5183 ASSERT_TRUE(upSequenceNum);
5184 // Don't finish the events yet, and send a key
5185 // Injection will succeed because we will eventually give up and send the key to the focused
5186 // window even if motions are still being processed.
5187
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005188 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005189 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005190 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005192 // Key will not be sent to the window, yet, because the window is still processing events
5193 // and the key remains pending, waiting for the touch events to be processed
5194 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5195 ASSERT_FALSE(keySequenceNum);
5196
5197 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005198 mFocusedWindow->setFocusable(false);
5199 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005201 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202
5203 // Focus events should precede the key events
5204 mUnfocusedWindow->consumeFocusEvent(true);
5205 mFocusedWindow->consumeFocusEvent(false);
5206
5207 // Finish the tap events, which should unblock dispatcher
5208 mUnfocusedWindow->finishEvent(*downSequenceNum);
5209 mUnfocusedWindow->finishEvent(*upSequenceNum);
5210
5211 // Now that all queues are cleared and no backlog in the connections, the key event
5212 // can finally go to the newly focused "mUnfocusedWindow".
5213 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5214 mFocusedWindow->assertNoEvents();
5215 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005216 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217}
5218
5219// When the touch stream is split across 2 windows, and one of them does not respond,
5220// then ANR should be raised and the touch should be canceled for the unresponsive window.
5221// The other window should not be affected by that.
5222TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5223 // Touch Window 1
5224 NotifyMotionArgs motionArgs =
5225 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5226 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5227 mDispatcher->notifyMotion(&motionArgs);
5228 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5229 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5230
5231 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005232 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5233 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234 mDispatcher->notifyMotion(&motionArgs);
5235
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 mUnfocusedWindow->consumeMotionDown();
5241 mFocusedWindow->consumeMotionDown();
5242 // Focused window may or may not receive ACTION_MOVE
5243 // But it should definitely receive ACTION_CANCEL due to the ANR
5244 InputEvent* event;
5245 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5246 ASSERT_TRUE(moveOrCancelSequenceNum);
5247 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5248 ASSERT_NE(nullptr, event);
5249 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5250 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5251 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5252 mFocusedWindow->consumeMotionCancel();
5253 } else {
5254 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5255 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005257 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5258 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005259
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005260 mUnfocusedWindow->assertNoEvents();
5261 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005262 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005263}
5264
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005265/**
5266 * If we have no focused window, and a key comes in, we start the ANR timer.
5267 * The focused application should add a focused window before the timer runs out to prevent ANR.
5268 *
5269 * If the user touches another application during this time, the key should be dropped.
5270 * Next, if a new focused window comes in, without toggling the focused application,
5271 * then no ANR should occur.
5272 *
5273 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5274 * but in some cases the policy may not update the focused application.
5275 */
5276TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5277 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5278 std::make_shared<FakeApplicationHandle>();
5279 focusedApplication->setDispatchingTimeout(60ms);
5280 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5281 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5282 mFocusedWindow->setFocusable(false);
5283
5284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5285 mFocusedWindow->consumeFocusEvent(false);
5286
5287 // Send a key. The ANR timer should start because there is no focused window.
5288 // 'focusedApplication' will get blamed if this timer completes.
5289 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005290 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005291 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005292 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5293 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005295
5296 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5297 // then the injected touches won't cause the focused event to get dropped.
5298 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5299 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5300 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5301 // For this test, it means that the key would get delivered to the window once it becomes
5302 // focused.
5303 std::this_thread::sleep_for(10ms);
5304
5305 // Touch unfocused window. This should force the pending key to get dropped.
5306 NotifyMotionArgs motionArgs =
5307 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5308 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5309 mDispatcher->notifyMotion(&motionArgs);
5310
5311 // We do not consume the motion right away, because that would require dispatcher to first
5312 // process (== drop) the key event, and by that time, ANR will be raised.
5313 // Set the focused window first.
5314 mFocusedWindow->setFocusable(true);
5315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5316 setFocusedWindow(mFocusedWindow);
5317 mFocusedWindow->consumeFocusEvent(true);
5318 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5319 // to another application. This could be a bug / behaviour in the policy.
5320
5321 mUnfocusedWindow->consumeMotionDown();
5322
5323 ASSERT_TRUE(mDispatcher->waitForIdle());
5324 // Should not ANR because we actually have a focused window. It was just added too slowly.
5325 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5326}
5327
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005328// These tests ensure we cannot send touch events to a window that's positioned behind a window
5329// that has feature NO_INPUT_CHANNEL.
5330// Layout:
5331// Top (closest to user)
5332// mNoInputWindow (above all windows)
5333// mBottomWindow
5334// Bottom (furthest from user)
5335class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5336 virtual void SetUp() override {
5337 InputDispatcherTest::SetUp();
5338
5339 mApplication = std::make_shared<FakeApplicationHandle>();
5340 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5341 "Window without input channel", ADISPLAY_ID_DEFAULT,
5342 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5343
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005344 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005345 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5346 // It's perfectly valid for this window to not have an associated input channel
5347
5348 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5349 ADISPLAY_ID_DEFAULT);
5350 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5351
5352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5353 }
5354
5355protected:
5356 std::shared_ptr<FakeApplicationHandle> mApplication;
5357 sp<FakeWindowHandle> mNoInputWindow;
5358 sp<FakeWindowHandle> mBottomWindow;
5359};
5360
5361TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5362 PointF touchedPoint = {10, 10};
5363
5364 NotifyMotionArgs motionArgs =
5365 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5366 ADISPLAY_ID_DEFAULT, {touchedPoint});
5367 mDispatcher->notifyMotion(&motionArgs);
5368
5369 mNoInputWindow->assertNoEvents();
5370 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5371 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5372 // and therefore should prevent mBottomWindow from receiving touches
5373 mBottomWindow->assertNoEvents();
5374}
5375
5376/**
5377 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5378 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5379 */
5380TEST_F(InputDispatcherMultiWindowOcclusionTests,
5381 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5382 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5383 "Window with input channel and NO_INPUT_CHANNEL",
5384 ADISPLAY_ID_DEFAULT);
5385
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005386 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005387 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5389
5390 PointF touchedPoint = {10, 10};
5391
5392 NotifyMotionArgs motionArgs =
5393 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5394 ADISPLAY_ID_DEFAULT, {touchedPoint});
5395 mDispatcher->notifyMotion(&motionArgs);
5396
5397 mNoInputWindow->assertNoEvents();
5398 mBottomWindow->assertNoEvents();
5399}
5400
Vishnu Nair958da932020-08-21 17:12:37 -07005401class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5402protected:
5403 std::shared_ptr<FakeApplicationHandle> mApp;
5404 sp<FakeWindowHandle> mWindow;
5405 sp<FakeWindowHandle> mMirror;
5406
5407 virtual void SetUp() override {
5408 InputDispatcherTest::SetUp();
5409 mApp = std::make_shared<FakeApplicationHandle>();
5410 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5411 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5412 mWindow->getToken());
5413 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5414 mWindow->setFocusable(true);
5415 mMirror->setFocusable(true);
5416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5417 }
5418};
5419
5420TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5421 // Request focus on a mirrored window
5422 setFocusedWindow(mMirror);
5423
5424 // window gets focused
5425 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5427 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005428 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5429}
5430
5431// A focused & mirrored window remains focused only if the window and its mirror are both
5432// focusable.
5433TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5434 setFocusedWindow(mMirror);
5435
5436 // window gets focused
5437 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5439 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005440 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5442 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005443 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5444
5445 mMirror->setFocusable(false);
5446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5447
5448 // window loses focus since one of the windows associated with the token in not focusable
5449 mWindow->consumeFocusEvent(false);
5450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005451 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5452 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005453 mWindow->assertNoEvents();
5454}
5455
5456// A focused & mirrored window remains focused until the window and its mirror both become
5457// invisible.
5458TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5459 setFocusedWindow(mMirror);
5460
5461 // window gets focused
5462 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5464 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005465 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5467 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005468 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5469
5470 mMirror->setVisible(false);
5471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5472
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5474 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005475 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5477 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005478 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5479
5480 mWindow->setVisible(false);
5481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5482
5483 // window loses focus only after all windows associated with the token become invisible.
5484 mWindow->consumeFocusEvent(false);
5485
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005486 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5487 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005488 mWindow->assertNoEvents();
5489}
5490
5491// A focused & mirrored window remains focused until both windows are removed.
5492TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5493 setFocusedWindow(mMirror);
5494
5495 // window gets focused
5496 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5498 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005499 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005500 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5501 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005502 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5503
5504 // single window is removed but the window token remains focused
5505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5506
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5508 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005509 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5511 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005512 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5513
5514 // Both windows are removed
5515 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5516 mWindow->consumeFocusEvent(false);
5517
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005518 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5519 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005520 mWindow->assertNoEvents();
5521}
5522
5523// Focus request can be pending until one window becomes visible.
5524TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5525 // Request focus on an invisible mirror.
5526 mWindow->setVisible(false);
5527 mMirror->setVisible(false);
5528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5529 setFocusedWindow(mMirror);
5530
5531 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005533 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005534 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005535
5536 mMirror->setVisible(true);
5537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5538
5539 // window gets focused
5540 mWindow->consumeFocusEvent(true);
5541 // window gets the pending key event
5542 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5543}
Prabir Pradhan99987712020-11-10 18:43:05 -08005544
5545class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5546protected:
5547 std::shared_ptr<FakeApplicationHandle> mApp;
5548 sp<FakeWindowHandle> mWindow;
5549 sp<FakeWindowHandle> mSecondWindow;
5550
5551 void SetUp() override {
5552 InputDispatcherTest::SetUp();
5553 mApp = std::make_shared<FakeApplicationHandle>();
5554 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5555 mWindow->setFocusable(true);
5556 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5557 mSecondWindow->setFocusable(true);
5558
5559 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5561
5562 setFocusedWindow(mWindow);
5563 mWindow->consumeFocusEvent(true);
5564 }
5565
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005566 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5567 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005568 mDispatcher->notifyPointerCaptureChanged(&args);
5569 }
5570
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005571 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5572 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005573 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005574 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5575 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005576 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005577 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 }
5579};
5580
5581TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5582 // Ensure that capture cannot be obtained for unfocused windows.
5583 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5584 mFakePolicy->assertSetPointerCaptureNotCalled();
5585 mSecondWindow->assertNoEvents();
5586
5587 // Ensure that capture can be enabled from the focus window.
5588 requestAndVerifyPointerCapture(mWindow, true);
5589
5590 // Ensure that capture cannot be disabled from a window that does not have capture.
5591 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5592 mFakePolicy->assertSetPointerCaptureNotCalled();
5593
5594 // Ensure that capture can be disabled from the window with capture.
5595 requestAndVerifyPointerCapture(mWindow, false);
5596}
5597
5598TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005599 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005600
5601 setFocusedWindow(mSecondWindow);
5602
5603 // Ensure that the capture disabled event was sent first.
5604 mWindow->consumeCaptureEvent(false);
5605 mWindow->consumeFocusEvent(false);
5606 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005607 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005608
5609 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005610 notifyPointerCaptureChanged({});
5611 notifyPointerCaptureChanged(request);
5612 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005613 mWindow->assertNoEvents();
5614 mSecondWindow->assertNoEvents();
5615 mFakePolicy->assertSetPointerCaptureNotCalled();
5616}
5617
5618TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005619 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005620
5621 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005622 notifyPointerCaptureChanged({});
5623 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005624
5625 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005626 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005627 mWindow->consumeCaptureEvent(false);
5628 mWindow->assertNoEvents();
5629}
5630
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005631TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5632 requestAndVerifyPointerCapture(mWindow, true);
5633
5634 // The first window loses focus.
5635 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005636 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005637 mWindow->consumeCaptureEvent(false);
5638
5639 // Request Pointer Capture from the second window before the notification from InputReader
5640 // arrives.
5641 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005642 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005643
5644 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005645 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005646
5647 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005648 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005649
5650 mSecondWindow->consumeFocusEvent(true);
5651 mSecondWindow->consumeCaptureEvent(true);
5652}
5653
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005654TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5655 // App repeatedly enables and disables capture.
5656 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5657 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5658 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5659 mFakePolicy->assertSetPointerCaptureCalled(false);
5660 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5661 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5662
5663 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5664 // first request is now stale, this should do nothing.
5665 notifyPointerCaptureChanged(firstRequest);
5666 mWindow->assertNoEvents();
5667
5668 // InputReader notifies that the second request was enabled.
5669 notifyPointerCaptureChanged(secondRequest);
5670 mWindow->consumeCaptureEvent(true);
5671}
5672
Prabir Pradhan7092e262022-05-03 16:51:09 +00005673TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5674 requestAndVerifyPointerCapture(mWindow, true);
5675
5676 // App toggles pointer capture off and on.
5677 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5678 mFakePolicy->assertSetPointerCaptureCalled(false);
5679
5680 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5681 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5682
5683 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5684 // preceding "disable" request.
5685 notifyPointerCaptureChanged(enableRequest);
5686
5687 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5688 // any notifications.
5689 mWindow->assertNoEvents();
5690}
5691
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005692class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5693protected:
5694 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005695
5696 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5697 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5698
5699 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5700 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5701
5702 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5703 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5704 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5705 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5706 MAXIMUM_OBSCURING_OPACITY);
5707
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005708 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005709 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005710 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005711
5712 sp<FakeWindowHandle> mTouchWindow;
5713
5714 virtual void SetUp() override {
5715 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005716 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005717 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5718 }
5719
5720 virtual void TearDown() override {
5721 InputDispatcherTest::TearDown();
5722 mTouchWindow.clear();
5723 }
5724
chaviw3277faf2021-05-19 16:45:23 -05005725 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5726 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005727 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005728 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005729 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005730 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005731 return window;
5732 }
5733
5734 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5735 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5736 sp<FakeWindowHandle> window =
5737 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5738 // Generate an arbitrary PID based on the UID
5739 window->setOwnerInfo(1777 + (uid % 10000), uid);
5740 return window;
5741 }
5742
5743 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5744 NotifyMotionArgs args =
5745 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5746 ADISPLAY_ID_DEFAULT, points);
5747 mDispatcher->notifyMotion(&args);
5748 }
5749};
5750
5751TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005752 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005753 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005755
5756 touch();
5757
5758 mTouchWindow->assertNoEvents();
5759}
5760
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005761TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005762 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5763 const sp<FakeWindowHandle>& w =
5764 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5766
5767 touch();
5768
5769 mTouchWindow->assertNoEvents();
5770}
5771
5772TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005773 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5774 const sp<FakeWindowHandle>& w =
5775 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5777
5778 touch();
5779
5780 w->assertNoEvents();
5781}
5782
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005783TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005784 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005786
5787 touch();
5788
5789 mTouchWindow->consumeAnyMotionDown();
5790}
5791
5792TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005793 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005794 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005795 w->setFrame(Rect(0, 0, 50, 50));
5796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005797
5798 touch({PointF{100, 100}});
5799
5800 mTouchWindow->consumeAnyMotionDown();
5801}
5802
5803TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005804 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005805 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5807
5808 touch();
5809
5810 mTouchWindow->consumeAnyMotionDown();
5811}
5812
5813TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5814 const sp<FakeWindowHandle>& w =
5815 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5816 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005817
5818 touch();
5819
5820 mTouchWindow->consumeAnyMotionDown();
5821}
5822
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005823TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5824 const sp<FakeWindowHandle>& w =
5825 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5827
5828 touch();
5829
5830 w->assertNoEvents();
5831}
5832
5833/**
5834 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5835 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5836 * window, the occluding window will still receive ACTION_OUTSIDE event.
5837 */
5838TEST_F(InputDispatcherUntrustedTouchesTest,
5839 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5840 const sp<FakeWindowHandle>& w =
5841 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005842 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5844
5845 touch();
5846
5847 w->consumeMotionOutside();
5848}
5849
5850TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5851 const sp<FakeWindowHandle>& w =
5852 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005853 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5855
5856 touch();
5857
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005858 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005859}
5860
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005861TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005862 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005863 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5864 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5866
5867 touch();
5868
5869 mTouchWindow->consumeAnyMotionDown();
5870}
5871
5872TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5873 const sp<FakeWindowHandle>& w =
5874 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5875 MAXIMUM_OBSCURING_OPACITY);
5876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005877
5878 touch();
5879
5880 mTouchWindow->consumeAnyMotionDown();
5881}
5882
5883TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005884 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005885 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5886 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5888
5889 touch();
5890
5891 mTouchWindow->assertNoEvents();
5892}
5893
5894TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5895 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5896 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005897 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5898 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005899 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005900 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5901 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5903
5904 touch();
5905
5906 mTouchWindow->assertNoEvents();
5907}
5908
5909TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5910 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5911 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005912 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5913 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005914 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005915 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5916 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5918
5919 touch();
5920
5921 mTouchWindow->consumeAnyMotionDown();
5922}
5923
5924TEST_F(InputDispatcherUntrustedTouchesTest,
5925 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5926 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005927 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5928 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005929 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005930 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5931 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5933
5934 touch();
5935
5936 mTouchWindow->consumeAnyMotionDown();
5937}
5938
5939TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5940 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005941 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5942 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005943 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005944 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5945 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005947
5948 touch();
5949
5950 mTouchWindow->assertNoEvents();
5951}
5952
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005953TEST_F(InputDispatcherUntrustedTouchesTest,
5954 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5955 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005956 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5957 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005958 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005959 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5960 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005961 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5962
5963 touch();
5964
5965 mTouchWindow->assertNoEvents();
5966}
5967
5968TEST_F(InputDispatcherUntrustedTouchesTest,
5969 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5970 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005971 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5972 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005973 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005974 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5975 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5977
5978 touch();
5979
5980 mTouchWindow->consumeAnyMotionDown();
5981}
5982
5983TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5984 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005985 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5986 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5988
5989 touch();
5990
5991 mTouchWindow->consumeAnyMotionDown();
5992}
5993
5994TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5995 const sp<FakeWindowHandle>& w =
5996 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5998
5999 touch();
6000
6001 mTouchWindow->consumeAnyMotionDown();
6002}
6003
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006004TEST_F(InputDispatcherUntrustedTouchesTest,
6005 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6006 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6007 const sp<FakeWindowHandle>& w =
6008 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6010
6011 touch();
6012
6013 mTouchWindow->assertNoEvents();
6014}
6015
6016TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6017 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6018 const sp<FakeWindowHandle>& w =
6019 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6021
6022 touch();
6023
6024 mTouchWindow->consumeAnyMotionDown();
6025}
6026
6027TEST_F(InputDispatcherUntrustedTouchesTest,
6028 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6029 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6030 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006031 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6032 OPACITY_ABOVE_THRESHOLD);
6033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6034
6035 touch();
6036
6037 mTouchWindow->consumeAnyMotionDown();
6038}
6039
6040TEST_F(InputDispatcherUntrustedTouchesTest,
6041 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6042 const sp<FakeWindowHandle>& w1 =
6043 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6044 OPACITY_BELOW_THRESHOLD);
6045 const sp<FakeWindowHandle>& w2 =
6046 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6047 OPACITY_BELOW_THRESHOLD);
6048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6049
6050 touch();
6051
6052 mTouchWindow->assertNoEvents();
6053}
6054
6055/**
6056 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6057 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6058 * (which alone would result in allowing touches) does not affect the blocking behavior.
6059 */
6060TEST_F(InputDispatcherUntrustedTouchesTest,
6061 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6062 const sp<FakeWindowHandle>& wB =
6063 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6064 OPACITY_BELOW_THRESHOLD);
6065 const sp<FakeWindowHandle>& wC =
6066 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6067 OPACITY_BELOW_THRESHOLD);
6068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6069
6070 touch();
6071
6072 mTouchWindow->assertNoEvents();
6073}
6074
6075/**
6076 * This test is testing that a window from a different UID but with same application token doesn't
6077 * block the touch. Apps can share the application token for close UI collaboration for example.
6078 */
6079TEST_F(InputDispatcherUntrustedTouchesTest,
6080 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6081 const sp<FakeWindowHandle>& w =
6082 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6083 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6085
6086 touch();
6087
6088 mTouchWindow->consumeAnyMotionDown();
6089}
6090
arthurhungb89ccb02020-12-30 16:19:01 +08006091class InputDispatcherDragTests : public InputDispatcherTest {
6092protected:
6093 std::shared_ptr<FakeApplicationHandle> mApp;
6094 sp<FakeWindowHandle> mWindow;
6095 sp<FakeWindowHandle> mSecondWindow;
6096 sp<FakeWindowHandle> mDragWindow;
6097
6098 void SetUp() override {
6099 InputDispatcherTest::SetUp();
6100 mApp = std::make_shared<FakeApplicationHandle>();
6101 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6102 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006103
6104 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6105 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006106
6107 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6108 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6109 }
6110
Arthur Hung54745652022-04-20 07:17:41 +00006111 void injectDown() {
arthurhungb89ccb02020-12-30 16:19:01 +08006112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6113 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6114 {50, 50}))
6115 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6116
6117 // Window should receive motion event.
6118 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006119 }
6120
6121 // Start performing drag, we will create a drag window and transfer touch to it.
6122 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6123 // Returns true on success.
6124 bool performDrag(bool sendDown = true) {
6125 if (sendDown) {
6126 injectDown();
6127 }
arthurhungb89ccb02020-12-30 16:19:01 +08006128
6129 // The drag window covers the entire display
6130 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6131 mDispatcher->setInputWindows(
6132 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6133
6134 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006135 bool transferred =
6136 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6137 true /* isDragDrop */);
6138 if (transferred) {
6139 mWindow->consumeMotionCancel();
6140 mDragWindow->consumeMotionDown();
6141 }
6142 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006143 }
arthurhung6d4bed92021-03-17 11:59:33 +08006144
6145 // Start performing drag, we will create a drag window and transfer touch to it.
6146 void performStylusDrag() {
6147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6148 injectMotionEvent(mDispatcher,
6149 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6150 AINPUT_SOURCE_STYLUS)
6151 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6152 .pointer(PointerBuilder(0,
6153 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6154 .x(50)
6155 .y(50))
6156 .build()));
6157 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6158
6159 // The drag window covers the entire display
6160 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6161 mDispatcher->setInputWindows(
6162 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6163
6164 // Transfer touch focus to the drag window
6165 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6166 true /* isDragDrop */);
6167 mWindow->consumeMotionCancel();
6168 mDragWindow->consumeMotionDown();
6169 }
arthurhungb89ccb02020-12-30 16:19:01 +08006170};
6171
6172TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6173 performDrag();
6174
6175 // Move on window.
6176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6177 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6178 ADISPLAY_ID_DEFAULT, {50, 50}))
6179 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6180 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6181 mWindow->consumeDragEvent(false, 50, 50);
6182 mSecondWindow->assertNoEvents();
6183
6184 // Move to another window.
6185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6186 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6187 ADISPLAY_ID_DEFAULT, {150, 50}))
6188 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6189 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6190 mWindow->consumeDragEvent(true, 150, 50);
6191 mSecondWindow->consumeDragEvent(false, 50, 50);
6192
6193 // Move back to original window.
6194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6195 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6196 ADISPLAY_ID_DEFAULT, {50, 50}))
6197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6198 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6199 mWindow->consumeDragEvent(false, 50, 50);
6200 mSecondWindow->consumeDragEvent(true, -50, 50);
6201
6202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6203 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6204 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6205 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6206 mWindow->assertNoEvents();
6207 mSecondWindow->assertNoEvents();
6208}
6209
arthurhungf452d0b2021-01-06 00:19:52 +08006210TEST_F(InputDispatcherDragTests, DragAndDrop) {
6211 performDrag();
6212
6213 // Move on window.
6214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6215 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6216 ADISPLAY_ID_DEFAULT, {50, 50}))
6217 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6218 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6219 mWindow->consumeDragEvent(false, 50, 50);
6220 mSecondWindow->assertNoEvents();
6221
6222 // Move to another window.
6223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6224 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6225 ADISPLAY_ID_DEFAULT, {150, 50}))
6226 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6227 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6228 mWindow->consumeDragEvent(true, 150, 50);
6229 mSecondWindow->consumeDragEvent(false, 50, 50);
6230
6231 // drop to another window.
6232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6233 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6234 {150, 50}))
6235 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6236 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6237 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6238 mWindow->assertNoEvents();
6239 mSecondWindow->assertNoEvents();
6240}
6241
arthurhung6d4bed92021-03-17 11:59:33 +08006242TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6243 performStylusDrag();
6244
6245 // Move on window and keep button pressed.
6246 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6247 injectMotionEvent(mDispatcher,
6248 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6249 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6250 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6251 .x(50)
6252 .y(50))
6253 .build()))
6254 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6255 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6256 mWindow->consumeDragEvent(false, 50, 50);
6257 mSecondWindow->assertNoEvents();
6258
6259 // Move to another window and release button, expect to drop item.
6260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6261 injectMotionEvent(mDispatcher,
6262 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6263 .buttonState(0)
6264 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6265 .x(150)
6266 .y(50))
6267 .build()))
6268 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6269 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6270 mWindow->assertNoEvents();
6271 mSecondWindow->assertNoEvents();
6272 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6273
6274 // nothing to the window.
6275 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6276 injectMotionEvent(mDispatcher,
6277 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6278 .buttonState(0)
6279 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6280 .x(150)
6281 .y(50))
6282 .build()))
6283 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6284 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6285 mWindow->assertNoEvents();
6286 mSecondWindow->assertNoEvents();
6287}
6288
Arthur Hung54745652022-04-20 07:17:41 +00006289TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08006290 performDrag();
6291
6292 // Set second window invisible.
6293 mSecondWindow->setVisible(false);
6294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6295
6296 // Move on window.
6297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6298 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6299 ADISPLAY_ID_DEFAULT, {50, 50}))
6300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6301 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6302 mWindow->consumeDragEvent(false, 50, 50);
6303 mSecondWindow->assertNoEvents();
6304
6305 // Move to another window.
6306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6307 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6308 ADISPLAY_ID_DEFAULT, {150, 50}))
6309 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6310 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6311 mWindow->consumeDragEvent(true, 150, 50);
6312 mSecondWindow->assertNoEvents();
6313
6314 // drop to another window.
6315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6316 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6317 {150, 50}))
6318 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6319 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6320 mFakePolicy->assertDropTargetEquals(nullptr);
6321 mWindow->assertNoEvents();
6322 mSecondWindow->assertNoEvents();
6323}
6324
Arthur Hung54745652022-04-20 07:17:41 +00006325TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
6326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6327 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6328 {50, 50}))
6329 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6330 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6331
6332 const MotionEvent secondFingerDownEvent =
6333 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6334 .displayId(ADISPLAY_ID_DEFAULT)
6335 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6336 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6337 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6338 .build();
6339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6340 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6341 InputEventInjectionSync::WAIT_FOR_RESULT))
6342 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6343 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6344
6345 // Should not perform drag and drop when window has multi fingers.
6346 ASSERT_FALSE(performDrag(false));
6347}
6348
6349TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6350 // First down on second window.
6351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6352 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6353 {150, 50}))
6354 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6355
6356 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6357
6358 // Second down on first window.
6359 const MotionEvent secondFingerDownEvent =
6360 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6361 .displayId(ADISPLAY_ID_DEFAULT)
6362 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6363 .pointer(
6364 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6365 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6366 .build();
6367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6368 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6369 InputEventInjectionSync::WAIT_FOR_RESULT))
6370 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6371 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6372
6373 // Perform drag and drop from first window.
6374 ASSERT_TRUE(performDrag(false));
6375
6376 // Move on window.
6377 const MotionEvent secondFingerMoveEvent =
6378 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6379 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6380 .pointer(
6381 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6382 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6383 .build();
6384 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6385 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6386 InputEventInjectionSync::WAIT_FOR_RESULT));
6387 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6388 mWindow->consumeDragEvent(false, 50, 50);
6389 mSecondWindow->consumeMotionMove();
6390
6391 // Release the drag pointer should perform drop.
6392 const MotionEvent secondFingerUpEvent =
6393 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6394 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6395 .pointer(
6396 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6397 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6398 .build();
6399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6400 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6401 InputEventInjectionSync::WAIT_FOR_RESULT));
6402 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6403 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6404 mWindow->assertNoEvents();
6405 mSecondWindow->consumeMotionMove();
6406}
6407
Vishnu Nair062a8672021-09-03 16:07:44 -07006408class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6409
6410TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6411 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6412 sp<FakeWindowHandle> window =
6413 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006414 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006415 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6416 window->setFocusable(true);
6417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6418 setFocusedWindow(window);
6419 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6420
6421 // With the flag set, window should not get any input
6422 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6423 mDispatcher->notifyKey(&keyArgs);
6424 window->assertNoEvents();
6425
6426 NotifyMotionArgs motionArgs =
6427 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6428 ADISPLAY_ID_DEFAULT);
6429 mDispatcher->notifyMotion(&motionArgs);
6430 window->assertNoEvents();
6431
6432 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006433 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6435
6436 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6437 mDispatcher->notifyKey(&keyArgs);
6438 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6439
6440 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6441 ADISPLAY_ID_DEFAULT);
6442 mDispatcher->notifyMotion(&motionArgs);
6443 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6444 window->assertNoEvents();
6445}
6446
6447TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6448 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6449 std::make_shared<FakeApplicationHandle>();
6450 sp<FakeWindowHandle> obscuringWindow =
6451 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6452 ADISPLAY_ID_DEFAULT);
6453 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6454 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006455 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006456 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6457 sp<FakeWindowHandle> window =
6458 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006459 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006460 window->setOwnerInfo(222, 222);
6461 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6462 window->setFocusable(true);
6463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6464 setFocusedWindow(window);
6465 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6466
6467 // With the flag set, window should not get any input
6468 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6469 mDispatcher->notifyKey(&keyArgs);
6470 window->assertNoEvents();
6471
6472 NotifyMotionArgs motionArgs =
6473 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6474 ADISPLAY_ID_DEFAULT);
6475 mDispatcher->notifyMotion(&motionArgs);
6476 window->assertNoEvents();
6477
6478 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006479 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6481
6482 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6483 mDispatcher->notifyKey(&keyArgs);
6484 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6485
6486 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6487 ADISPLAY_ID_DEFAULT);
6488 mDispatcher->notifyMotion(&motionArgs);
6489 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6490 window->assertNoEvents();
6491}
6492
6493TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6494 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6495 std::make_shared<FakeApplicationHandle>();
6496 sp<FakeWindowHandle> obscuringWindow =
6497 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6498 ADISPLAY_ID_DEFAULT);
6499 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6500 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006501 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006502 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6503 sp<FakeWindowHandle> window =
6504 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006505 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006506 window->setOwnerInfo(222, 222);
6507 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6508 window->setFocusable(true);
6509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6510 setFocusedWindow(window);
6511 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6512
6513 // With the flag set, window should not get any input
6514 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6515 mDispatcher->notifyKey(&keyArgs);
6516 window->assertNoEvents();
6517
6518 NotifyMotionArgs motionArgs =
6519 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6520 ADISPLAY_ID_DEFAULT);
6521 mDispatcher->notifyMotion(&motionArgs);
6522 window->assertNoEvents();
6523
6524 // When the window is no longer obscured because it went on top, it should get input
6525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6526
6527 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6528 mDispatcher->notifyKey(&keyArgs);
6529 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6530
6531 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6532 ADISPLAY_ID_DEFAULT);
6533 mDispatcher->notifyMotion(&motionArgs);
6534 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6535 window->assertNoEvents();
6536}
6537
Antonio Kantekf16f2832021-09-28 04:39:20 +00006538class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6539protected:
6540 std::shared_ptr<FakeApplicationHandle> mApp;
6541 sp<FakeWindowHandle> mWindow;
6542 sp<FakeWindowHandle> mSecondWindow;
6543
6544 void SetUp() override {
6545 InputDispatcherTest::SetUp();
6546
6547 mApp = std::make_shared<FakeApplicationHandle>();
6548 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6549 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006550 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006551 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6552 mSecondWindow->setFocusable(true);
6553
6554 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006556 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006557
6558 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006559 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6560 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006561 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6562 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6563 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006564 }
6565
Antonio Kantekea47acb2021-12-23 12:41:25 -08006566 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006567 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006568 mWindow->consumeTouchModeEvent(inTouchMode);
6569 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6570 }
6571};
6572
Antonio Kantek26defcf2022-02-08 01:12:27 +00006573TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006574 const WindowInfo& windowInfo = *mWindow->getInfo();
6575 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6576 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006577}
6578
Antonio Kantek26defcf2022-02-08 01:12:27 +00006579TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6580 const WindowInfo& windowInfo = *mWindow->getInfo();
6581 int32_t ownerPid = windowInfo.ownerPid;
6582 int32_t ownerUid = windowInfo.ownerUid;
6583 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6584 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6585 ownerUid, /* hasPermission */ false));
6586 mWindow->assertNoEvents();
6587 mSecondWindow->assertNoEvents();
6588}
6589
6590TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6591 const WindowInfo& windowInfo = *mWindow->getInfo();
6592 int32_t ownerPid = windowInfo.ownerPid;
6593 int32_t ownerUid = windowInfo.ownerUid;
6594 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6595 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6596 /* hasPermission */ true);
6597}
6598
Antonio Kantekf16f2832021-09-28 04:39:20 +00006599TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006600 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006601 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6602 windowInfo.ownerPid, windowInfo.ownerUid,
6603 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006604 mWindow->assertNoEvents();
6605 mSecondWindow->assertNoEvents();
6606}
6607
Antonio Kantek48710e42022-03-24 14:19:30 -07006608TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6609 // Interact with the window first.
6610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6611 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6612 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6613
6614 // Then remove focus.
6615 mWindow->setFocusable(false);
6616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6617
6618 // Assert that caller can switch touch mode by owning one of the last interacted window.
6619 const WindowInfo& windowInfo = *mWindow->getInfo();
6620 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6621 windowInfo.ownerPid, windowInfo.ownerUid,
6622 /* hasPermission= */ false));
6623}
6624
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006625class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6626public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006627 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006628 std::shared_ptr<FakeApplicationHandle> application =
6629 std::make_shared<FakeApplicationHandle>();
6630 std::string name = "Fake Spy ";
6631 name += std::to_string(mSpyCount++);
6632 sp<FakeWindowHandle> spy =
6633 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006634 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006635 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006636 return spy;
6637 }
6638
6639 sp<FakeWindowHandle> createForeground() {
6640 std::shared_ptr<FakeApplicationHandle> application =
6641 std::make_shared<FakeApplicationHandle>();
6642 sp<FakeWindowHandle> window =
6643 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006644 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006645 return window;
6646 }
6647
6648private:
6649 int mSpyCount{0};
6650};
6651
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006652using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006653/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006654 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6655 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006656TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6657 ScopedSilentDeath _silentDeath;
6658
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006659 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006660 spy->setTrustedOverlay(false);
6661 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6662 ".* not a trusted overlay");
6663}
6664
6665/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006666 * Input injection into a display with a spy window but no foreground windows should succeed.
6667 */
6668TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006669 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6671
6672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6673 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6675 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6676}
6677
6678/**
6679 * Verify the order in which different input windows receive events. The touched foreground window
6680 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6681 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6682 * receive events before ones belows it.
6683 *
6684 * Here, we set up a scenario with four windows in the following Z order from the top:
6685 * spy1, spy2, window, spy3.
6686 * We then inject an event and verify that the foreground "window" receives it first, followed by
6687 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6688 * window.
6689 */
6690TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6691 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006692 auto spy1 = createSpy();
6693 auto spy2 = createSpy();
6694 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6696 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6697 const size_t numChannels = channels.size();
6698
Michael Wright8e9a8562022-02-09 13:44:29 +00006699 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006700 if (!epollFd.ok()) {
6701 FAIL() << "Failed to create epoll fd";
6702 }
6703
6704 for (size_t i = 0; i < numChannels; i++) {
6705 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6706 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6707 FAIL() << "Failed to add fd to epoll";
6708 }
6709 }
6710
6711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6714
6715 std::vector<size_t> eventOrder;
6716 std::vector<struct epoll_event> events(numChannels);
6717 for (;;) {
6718 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6719 (100ms).count());
6720 if (nFds < 0) {
6721 FAIL() << "Failed to call epoll_wait";
6722 }
6723 if (nFds == 0) {
6724 break; // epoll_wait timed out
6725 }
6726 for (int i = 0; i < nFds; i++) {
6727 ASSERT_EQ(EPOLLIN, events[i].events);
6728 eventOrder.push_back(events[i].data.u64);
6729 channels[i]->consumeMotionDown();
6730 }
6731 }
6732
6733 // Verify the order in which the events were received.
6734 EXPECT_EQ(3u, eventOrder.size());
6735 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6736 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6737 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6738}
6739
6740/**
6741 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6742 */
6743TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6744 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006745 auto spy = createSpy();
6746 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6748
6749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6750 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6752 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6753 spy->assertNoEvents();
6754}
6755
6756/**
6757 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6758 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6759 * to the window.
6760 */
6761TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6762 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006763 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006764 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6766
6767 // Inject an event outside the spy window's touchable region.
6768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6770 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6771 window->consumeMotionDown();
6772 spy->assertNoEvents();
6773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6774 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6776 window->consumeMotionUp();
6777 spy->assertNoEvents();
6778
6779 // Inject an event inside the spy window's touchable region.
6780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6782 {5, 10}))
6783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6784 window->consumeMotionDown();
6785 spy->consumeMotionDown();
6786}
6787
6788/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006789 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006790 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006791 */
6792TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6793 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006794 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006795 auto spy = createSpy();
6796 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006797 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006798 spy->setFrame(Rect{0, 0, 20, 20});
6799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6800
6801 // Inject an event outside the spy window's frame and touchable region.
6802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006803 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6804 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006805 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6806 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006807 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006808}
6809
6810/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006811 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6812 * pointers that are down within its bounds.
6813 */
6814TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6815 auto windowLeft = createForeground();
6816 windowLeft->setFrame({0, 0, 100, 200});
6817 auto windowRight = createForeground();
6818 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006819 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006820 spy->setFrame({0, 0, 200, 200});
6821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6822
6823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6825 {50, 50}))
6826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6827 windowLeft->consumeMotionDown();
6828 spy->consumeMotionDown();
6829
6830 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006831 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006832 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6833 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6834 .pointer(
6835 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6836 .build();
6837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6838 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6839 InputEventInjectionSync::WAIT_FOR_RESULT))
6840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6841 windowRight->consumeMotionDown();
6842 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6843}
6844
6845/**
6846 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6847 * the spy should receive the second pointer with ACTION_DOWN.
6848 */
6849TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6850 auto window = createForeground();
6851 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006852 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006853 spyRight->setFrame({100, 0, 200, 200});
6854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6855
6856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6857 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6858 {50, 50}))
6859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6860 window->consumeMotionDown();
6861 spyRight->assertNoEvents();
6862
6863 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006864 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006865 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6866 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6867 .pointer(
6868 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6869 .build();
6870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6871 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6872 InputEventInjectionSync::WAIT_FOR_RESULT))
6873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6874 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6875 spyRight->consumeMotionDown();
6876}
6877
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006878/**
6879 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6880 * windows should be allowed to control split touch.
6881 */
6882TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006883 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006884 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006885 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006886 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006887
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006888 auto window = createForeground();
6889 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006890
6891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6892
6893 // First finger down, no window touched.
6894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6896 {100, 200}))
6897 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6898 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6899 window->assertNoEvents();
6900
6901 // Second finger down on window, the window should receive touch down.
6902 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006903 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006904 .displayId(ADISPLAY_ID_DEFAULT)
6905 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6906 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6907 .x(100)
6908 .y(200))
6909 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6910 .build();
6911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6912 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6913 InputEventInjectionSync::WAIT_FOR_RESULT))
6914 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6915
6916 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6917 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6918}
6919
6920/**
6921 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6922 * do not receive key events.
6923 */
6924TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006925 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006926 spy->setFocusable(false);
6927
6928 auto window = createForeground();
6929 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6930 setFocusedWindow(window);
6931 window->consumeFocusEvent(true);
6932
6933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6934 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6935 window->consumeKeyDown(ADISPLAY_ID_NONE);
6936
6937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6938 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6939 window->consumeKeyUp(ADISPLAY_ID_NONE);
6940
6941 spy->assertNoEvents();
6942}
6943
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00006944using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
6945
6946/**
6947 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
6948 * are currently sent to any other windows - including other spy windows - will also be cancelled.
6949 */
6950TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
6951 auto window = createForeground();
6952 auto spy1 = createSpy();
6953 auto spy2 = createSpy();
6954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6955
6956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6957 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6959 window->consumeMotionDown();
6960 spy1->consumeMotionDown();
6961 spy2->consumeMotionDown();
6962
6963 // Pilfer pointers from the second spy window.
6964 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
6965 spy2->assertNoEvents();
6966 spy1->consumeMotionCancel();
6967 window->consumeMotionCancel();
6968
6969 // The rest of the gesture should only be sent to the second spy window.
6970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6971 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6972 ADISPLAY_ID_DEFAULT))
6973 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6974 spy2->consumeMotionMove();
6975 spy1->assertNoEvents();
6976 window->assertNoEvents();
6977}
6978
6979/**
6980 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6981 * in the middle of the gesture.
6982 */
6983TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
6984 auto window = createForeground();
6985 auto spy = createSpy();
6986 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6987
6988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6989 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6990 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6991 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6992 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6993
6994 window->releaseChannel();
6995
6996 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6997
6998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6999 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7000 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7001 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7002}
7003
7004/**
7005 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7006 * the spy, but not to any other windows.
7007 */
7008TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7009 auto spy = createSpy();
7010 auto window = createForeground();
7011
7012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7013
7014 // First finger down on the window and the spy.
7015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7017 {100, 200}))
7018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7019 spy->consumeMotionDown();
7020 window->consumeMotionDown();
7021
7022 // Spy window pilfers the pointers.
7023 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7024 window->consumeMotionCancel();
7025
7026 // Second finger down on the window and spy, but the window should not receive the pointer down.
7027 const MotionEvent secondFingerDownEvent =
7028 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7029 .displayId(ADISPLAY_ID_DEFAULT)
7030 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7031 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7032 .x(100)
7033 .y(200))
7034 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7035 .build();
7036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7037 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7038 InputEventInjectionSync::WAIT_FOR_RESULT))
7039 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7040
7041 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7042
7043 // Third finger goes down outside all windows, so injection should fail.
7044 const MotionEvent thirdFingerDownEvent =
7045 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7046 .displayId(ADISPLAY_ID_DEFAULT)
7047 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7048 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7049 .x(100)
7050 .y(200))
7051 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7052 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7053 .build();
7054 ASSERT_EQ(InputEventInjectionResult::FAILED,
7055 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7056 InputEventInjectionSync::WAIT_FOR_RESULT))
7057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7058
7059 spy->assertNoEvents();
7060 window->assertNoEvents();
7061}
7062
7063/**
7064 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7065 */
7066TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7067 auto spy = createSpy();
7068 spy->setFrame(Rect(0, 0, 100, 100));
7069 auto window = createForeground();
7070 window->setFrame(Rect(0, 0, 200, 200));
7071
7072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7073
7074 // First finger down on the window only
7075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7077 {150, 150}))
7078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7079 window->consumeMotionDown();
7080
7081 // Second finger down on the spy and window
7082 const MotionEvent secondFingerDownEvent =
7083 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7084 .displayId(ADISPLAY_ID_DEFAULT)
7085 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7086 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7087 .x(150)
7088 .y(150))
7089 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7090 .build();
7091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7092 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7093 InputEventInjectionSync::WAIT_FOR_RESULT))
7094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7095 spy->consumeMotionDown();
7096 window->consumeMotionPointerDown(1);
7097
7098 // Third finger down on the spy and window
7099 const MotionEvent thirdFingerDownEvent =
7100 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7101 .displayId(ADISPLAY_ID_DEFAULT)
7102 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7103 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7104 .x(150)
7105 .y(150))
7106 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7107 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7108 .build();
7109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7110 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7111 InputEventInjectionSync::WAIT_FOR_RESULT))
7112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7113 spy->consumeMotionPointerDown(1);
7114 window->consumeMotionPointerDown(2);
7115
7116 // Spy window pilfers the pointers.
7117 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7118 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7119 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7120
7121 spy->assertNoEvents();
7122 window->assertNoEvents();
7123}
7124
7125/**
7126 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7127 * other windows should be canceled. If this results in the cancellation of all pointers for some
7128 * window, then that window should receive ACTION_CANCEL.
7129 */
7130TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7131 auto spy = createSpy();
7132 spy->setFrame(Rect(0, 0, 100, 100));
7133 auto window = createForeground();
7134 window->setFrame(Rect(0, 0, 200, 200));
7135
7136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7137
7138 // First finger down on both spy and window
7139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7140 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7141 {10, 10}))
7142 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7143 window->consumeMotionDown();
7144 spy->consumeMotionDown();
7145
7146 // Second finger down on the spy and window
7147 const MotionEvent secondFingerDownEvent =
7148 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7149 .displayId(ADISPLAY_ID_DEFAULT)
7150 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7151 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7152 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7153 .build();
7154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7155 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7156 InputEventInjectionSync::WAIT_FOR_RESULT))
7157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7158 spy->consumeMotionPointerDown(1);
7159 window->consumeMotionPointerDown(1);
7160
7161 // Spy window pilfers the pointers.
7162 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7163 window->consumeMotionCancel();
7164
7165 spy->assertNoEvents();
7166 window->assertNoEvents();
7167}
7168
7169/**
7170 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7171 * be sent to other windows
7172 */
7173TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7174 auto spy = createSpy();
7175 spy->setFrame(Rect(0, 0, 100, 100));
7176 auto window = createForeground();
7177 window->setFrame(Rect(0, 0, 200, 200));
7178
7179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7180
7181 // First finger down on both window and spy
7182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7183 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7184 {10, 10}))
7185 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7186 window->consumeMotionDown();
7187 spy->consumeMotionDown();
7188
7189 // Spy window pilfers the pointers.
7190 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7191 window->consumeMotionCancel();
7192
7193 // Second finger down on the window only
7194 const MotionEvent secondFingerDownEvent =
7195 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7196 .displayId(ADISPLAY_ID_DEFAULT)
7197 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7198 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7199 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7200 .x(150)
7201 .y(150))
7202 .build();
7203 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7204 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7205 InputEventInjectionSync::WAIT_FOR_RESULT))
7206 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7207 window->consumeMotionDown();
7208 window->assertNoEvents();
7209
7210 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7211 spy->consumeMotionMove();
7212 spy->assertNoEvents();
7213}
7214
Prabir Pradhand65552b2021-10-07 11:23:50 -07007215class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7216public:
7217 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7218 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7219 std::make_shared<FakeApplicationHandle>();
7220 sp<FakeWindowHandle> overlay =
7221 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7222 ADISPLAY_ID_DEFAULT);
7223 overlay->setFocusable(false);
7224 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007225 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007226 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007227 overlay->setTrustedOverlay(true);
7228
7229 std::shared_ptr<FakeApplicationHandle> application =
7230 std::make_shared<FakeApplicationHandle>();
7231 sp<FakeWindowHandle> window =
7232 new FakeWindowHandle(application, mDispatcher, "Application window",
7233 ADISPLAY_ID_DEFAULT);
7234 window->setFocusable(true);
7235 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007236
7237 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7239 setFocusedWindow(window);
7240 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7241 return {std::move(overlay), std::move(window)};
7242 }
7243
7244 void sendFingerEvent(int32_t action) {
7245 NotifyMotionArgs motionArgs =
7246 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7247 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7248 mDispatcher->notifyMotion(&motionArgs);
7249 }
7250
7251 void sendStylusEvent(int32_t action) {
7252 NotifyMotionArgs motionArgs =
7253 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7254 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7255 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7256 mDispatcher->notifyMotion(&motionArgs);
7257 }
7258};
7259
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007260using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7261
7262TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7263 ScopedSilentDeath _silentDeath;
7264
Prabir Pradhand65552b2021-10-07 11:23:50 -07007265 auto [overlay, window] = setupStylusOverlayScenario();
7266 overlay->setTrustedOverlay(false);
7267 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7268 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7269 ".* not a trusted overlay");
7270}
7271
7272TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7273 auto [overlay, window] = setupStylusOverlayScenario();
7274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7275
7276 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7277 overlay->consumeMotionDown();
7278 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7279 overlay->consumeMotionUp();
7280
7281 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7282 window->consumeMotionDown();
7283 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7284 window->consumeMotionUp();
7285
7286 overlay->assertNoEvents();
7287 window->assertNoEvents();
7288}
7289
7290TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7291 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007292 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7294
7295 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7296 overlay->consumeMotionDown();
7297 window->consumeMotionDown();
7298 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7299 overlay->consumeMotionUp();
7300 window->consumeMotionUp();
7301
7302 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7303 window->consumeMotionDown();
7304 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7305 window->consumeMotionUp();
7306
7307 overlay->assertNoEvents();
7308 window->assertNoEvents();
7309}
7310
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007311/**
7312 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7313 * The scenario is as follows:
7314 * - The stylus interceptor overlay is configured as a spy window.
7315 * - The stylus interceptor spy receives the start of a new stylus gesture.
7316 * - It pilfers pointers and then configures itself to no longer be a spy.
7317 * - The stylus interceptor continues to receive the rest of the gesture.
7318 */
7319TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7320 auto [overlay, window] = setupStylusOverlayScenario();
7321 overlay->setSpy(true);
7322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7323
7324 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7325 overlay->consumeMotionDown();
7326 window->consumeMotionDown();
7327
7328 // The interceptor pilfers the pointers.
7329 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7330 window->consumeMotionCancel();
7331
7332 // The interceptor configures itself so that it is no longer a spy.
7333 overlay->setSpy(false);
7334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7335
7336 // It continues to receive the rest of the stylus gesture.
7337 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7338 overlay->consumeMotionMove();
7339 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7340 overlay->consumeMotionUp();
7341
7342 window->assertNoEvents();
7343}
7344
Prabir Pradhan5735a322022-04-11 17:23:34 +00007345struct User {
7346 int32_t mPid;
7347 int32_t mUid;
7348 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7349 std::unique_ptr<InputDispatcher>& mDispatcher;
7350
7351 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7352 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7353
7354 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7355 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7356 ADISPLAY_ID_DEFAULT, {100, 200},
7357 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7358 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7359 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7360 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7361 }
7362
7363 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7364 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7365 InputEventInjectionSync::WAIT_FOR_RESULT,
7366 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7367 mPolicyFlags);
7368 }
7369
7370 sp<FakeWindowHandle> createWindow() const {
7371 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7372 std::make_shared<FakeApplicationHandle>();
7373 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7374 "Owned Window", ADISPLAY_ID_DEFAULT);
7375 window->setOwnerInfo(mPid, mUid);
7376 return window;
7377 }
7378};
7379
7380using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7381
7382TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7383 auto owner = User(mDispatcher, 10, 11);
7384 auto window = owner.createWindow();
7385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7386
7387 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7388 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7389 window->consumeMotionDown();
7390
7391 setFocusedWindow(window);
7392 window->consumeFocusEvent(true);
7393
7394 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7395 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7396 window->consumeKeyDown(ADISPLAY_ID_NONE);
7397}
7398
7399TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7400 auto owner = User(mDispatcher, 10, 11);
7401 auto window = owner.createWindow();
7402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7403
7404 auto rando = User(mDispatcher, 20, 21);
7405 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7406 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7407
7408 setFocusedWindow(window);
7409 window->consumeFocusEvent(true);
7410
7411 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7412 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7413 window->assertNoEvents();
7414}
7415
7416TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7417 auto owner = User(mDispatcher, 10, 11);
7418 auto window = owner.createWindow();
7419 auto spy = owner.createWindow();
7420 spy->setSpy(true);
7421 spy->setTrustedOverlay(true);
7422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7423
7424 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7425 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7426 spy->consumeMotionDown();
7427 window->consumeMotionDown();
7428}
7429
7430TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7431 auto owner = User(mDispatcher, 10, 11);
7432 auto window = owner.createWindow();
7433
7434 auto rando = User(mDispatcher, 20, 21);
7435 auto randosSpy = rando.createWindow();
7436 randosSpy->setSpy(true);
7437 randosSpy->setTrustedOverlay(true);
7438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7439
7440 // The event is targeted at owner's window, so injection should succeed, but the spy should
7441 // not receive the event.
7442 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7443 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7444 randosSpy->assertNoEvents();
7445 window->consumeMotionDown();
7446}
7447
7448TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7449 auto owner = User(mDispatcher, 10, 11);
7450 auto window = owner.createWindow();
7451
7452 auto rando = User(mDispatcher, 20, 21);
7453 auto randosSpy = rando.createWindow();
7454 randosSpy->setSpy(true);
7455 randosSpy->setTrustedOverlay(true);
7456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7457
7458 // A user that has injection permission can inject into any window.
7459 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7460 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7461 ADISPLAY_ID_DEFAULT));
7462 randosSpy->consumeMotionDown();
7463 window->consumeMotionDown();
7464
7465 setFocusedWindow(randosSpy);
7466 randosSpy->consumeFocusEvent(true);
7467
7468 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7469 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7470 window->assertNoEvents();
7471}
7472
7473TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7474 auto owner = User(mDispatcher, 10, 11);
7475 auto window = owner.createWindow();
7476
7477 auto rando = User(mDispatcher, 20, 21);
7478 auto randosWindow = rando.createWindow();
7479 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7480 randosWindow->setWatchOutsideTouch(true);
7481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7482
7483 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7484 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7485 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7486 window->consumeMotionDown();
7487 randosWindow->consumeMotionOutside();
7488}
7489
Garfield Tane84e6f92019-08-29 17:28:41 -07007490} // namespace android::inputdispatcher