blob: 70fd25c1aa3d5144e7df953793e22dd684e64062 [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);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000061static constexpr int32_t POINTER_3_DOWN =
62 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080063static constexpr int32_t POINTER_1_UP =
64 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
65
Prabir Pradhan5735a322022-04-11 17:23:34 +000066// The default pid and uid for windows created by the test.
67static constexpr int32_t WINDOW_PID = 999;
68static constexpr int32_t WINDOW_UID = 1001;
69
70// The default policy flags to use for event injection by tests.
71static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000073// An arbitrary pid of the gesture monitor window
74static constexpr int32_t MONITOR_PID = 2001;
75
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080076static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
77
chaviwd1c23182019-12-20 18:44:56 -080078struct PointF {
79 float x;
80 float y;
81};
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
Gang Wang342c9272020-01-13 13:15:04 -050083/**
84 * Return a DOWN key event with KEYCODE_A.
85 */
86static KeyEvent getTestKeyEvent() {
87 KeyEvent event;
88
Garfield Tanfbe732e2020-01-24 11:26:14 -080089 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
90 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
91 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050092 return event;
93}
94
Siarhei Vishniakouca205502021-07-16 21:31:58 +000095static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
96 ASSERT_EQ(expectedAction, receivedAction)
97 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
98 << MotionEvent::actionToString(receivedAction);
99}
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// --- FakeInputDispatcherPolicy ---
102
103class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
104 InputDispatcherConfiguration mConfig;
105
Prabir Pradhanedd96402022-02-15 01:46:16 -0800106 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000109 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000112 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800113
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800114 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700115 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
116 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
117 EXPECT_EQ(event.getDisplayId(), args.displayId);
118
119 const auto& keyEvent = static_cast<const KeyEvent&>(event);
120 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
121 EXPECT_EQ(keyEvent.getAction(), args.action);
122 });
Jackal Guof9696682018-10-05 12:23:23 +0800123 }
124
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700125 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
126 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
127 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
128 EXPECT_EQ(event.getDisplayId(), args.displayId);
129
130 const auto& motionEvent = static_cast<const MotionEvent&>(event);
131 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
132 EXPECT_EQ(motionEvent.getAction(), args.action);
133 EXPECT_EQ(motionEvent.getX(0), point.x);
134 EXPECT_EQ(motionEvent.getY(0), point.y);
135 EXPECT_EQ(motionEvent.getRawX(0), point.x);
136 EXPECT_EQ(motionEvent.getRawY(0), point.y);
137 });
Jackal Guof9696682018-10-05 12:23:23 +0800138 }
139
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700140 void assertFilterInputEventWasNotCalled() {
141 std::scoped_lock lock(mLock);
142 ASSERT_EQ(nullptr, mFilteredEvent);
143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800145 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700146 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 ASSERT_TRUE(mConfigurationChangedTime)
148 << "Timed out waiting for configuration changed call";
149 ASSERT_EQ(*mConfigurationChangedTime, when);
150 mConfigurationChangedTime = std::nullopt;
151 }
152
153 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700154 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800155 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800156 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800157 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
158 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
159 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
160 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
161 mLastNotifySwitch = std::nullopt;
162 }
163
chaviwfd6d3512019-03-25 13:23:49 -0700164 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700165 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800166 ASSERT_EQ(touchedToken, mOnPointerDownToken);
167 mOnPointerDownToken.clear();
168 }
169
170 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700171 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800172 ASSERT_TRUE(mOnPointerDownToken == nullptr)
173 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700174 }
175
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700176 // This function must be called soon after the expected ANR timer starts,
177 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700179 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500180 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800181 std::unique_lock lock(mLock);
182 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500183 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800184 ASSERT_NO_FATAL_FAILURE(
185 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700187 }
188
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000189 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800190 const sp<WindowInfoHandle>& window) {
191 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
192 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
193 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500194 }
195
Prabir Pradhanedd96402022-02-15 01:46:16 -0800196 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
197 const sp<IBinder>& expectedToken,
198 int32_t expectedPid) {
199 std::unique_lock lock(mLock);
200 android::base::ScopedLockAssertion assumeLocked(mLock);
201 AnrResult result;
202 ASSERT_NO_FATAL_FAILURE(result =
203 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
204 const auto& [token, pid] = result;
205 ASSERT_EQ(expectedToken, token);
206 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500207 }
208
Prabir Pradhanedd96402022-02-15 01:46:16 -0800209 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000210 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500211 std::unique_lock lock(mLock);
212 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800213 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
214 const auto& [token, _] = result;
215 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000216 }
217
Prabir Pradhanedd96402022-02-15 01:46:16 -0800218 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
219 int32_t expectedPid) {
220 std::unique_lock lock(mLock);
221 android::base::ScopedLockAssertion assumeLocked(mLock);
222 AnrResult result;
223 ASSERT_NO_FATAL_FAILURE(
224 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
225 const auto& [token, pid] = result;
226 ASSERT_EQ(expectedToken, token);
227 ASSERT_EQ(expectedPid, pid);
228 }
229
230 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000231 sp<IBinder> getResponsiveWindowToken() {
232 std::unique_lock lock(mLock);
233 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800234 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
235 const auto& [token, _] = result;
236 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700237 }
238
239 void assertNotifyAnrWasNotCalled() {
240 std::scoped_lock lock(mLock);
241 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800242 ASSERT_TRUE(mAnrWindows.empty());
243 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500244 << "ANR was not called, but please also consume the 'connection is responsive' "
245 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700246 }
247
Garfield Tan1c7bc862020-01-28 13:24:04 -0800248 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
249 mConfig.keyRepeatTimeout = timeout;
250 mConfig.keyRepeatDelay = delay;
251 }
252
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000253 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800254 std::unique_lock lock(mLock);
255 base::ScopedLockAssertion assumeLocked(mLock);
256
257 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
258 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000259 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800260 enabled;
261 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000262 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
263 << ") to be called.";
264 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800265 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000266 auto request = *mPointerCaptureRequest;
267 mPointerCaptureRequest.reset();
268 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 }
270
271 void assertSetPointerCaptureNotCalled() {
272 std::unique_lock lock(mLock);
273 base::ScopedLockAssertion assumeLocked(mLock);
274
275 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000276 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800277 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800279 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000280 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 }
282
arthurhungf452d0b2021-01-06 00:19:52 +0800283 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
284 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800285 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800286 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800287 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800288 }
289
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800290 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
291 std::unique_lock lock(mLock);
292 base::ScopedLockAssertion assumeLocked(mLock);
293 std::optional<sp<IBinder>> receivedToken =
294 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
295 mNotifyInputChannelBroken);
296 ASSERT_TRUE(receivedToken.has_value());
297 ASSERT_EQ(token, *receivedToken);
298 }
299
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800300 /**
301 * Set policy timeout. A value of zero means next key will not be intercepted.
302 */
303 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
304 mInterceptKeyTimeout = timeout;
305 }
306
Michael Wrightd02c5b62014-02-10 15:10:22 -0800307private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700308 std::mutex mLock;
309 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
310 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
311 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
312 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800313
Prabir Pradhan99987712020-11-10 18:43:05 -0800314 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000315
316 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800317
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700318 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700319 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800320 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
321 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700322 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800323 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
324 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700325
arthurhungf452d0b2021-01-06 00:19:52 +0800326 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800327 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800328
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800329 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
330
Prabir Pradhanedd96402022-02-15 01:46:16 -0800331 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
332 // for a specific container to become non-empty. When the container is non-empty, return the
333 // first entry from the container and erase it.
334 template <class T>
335 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
336 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
337 // If there is an ANR, Dispatcher won't be idle because there are still events
338 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
339 // before checking if ANR was called.
340 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
341 // to provide it some time to act. 100ms seems reasonable.
342 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
343 const std::chrono::time_point start = std::chrono::steady_clock::now();
344 std::optional<T> token =
345 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
346 if (!token.has_value()) {
347 ADD_FAILURE() << "Did not receive the ANR callback";
348 return {};
349 }
350
351 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
352 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
353 // the dispatcher started counting before this function was called
354 if (std::chrono::abs(timeout - waited) > 100ms) {
355 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
356 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
357 << "ms, but waited "
358 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
359 << "ms instead";
360 }
361 return *token;
362 }
363
364 template <class T>
365 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
366 std::queue<T>& storage,
367 std::unique_lock<std::mutex>& lock,
368 std::condition_variable& condition)
369 REQUIRES(mLock) {
370 condition.wait_for(lock, timeout,
371 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
372 if (storage.empty()) {
373 ADD_FAILURE() << "Did not receive the expected callback";
374 return std::nullopt;
375 }
376 T item = storage.front();
377 storage.pop();
378 return std::make_optional(item);
379 }
380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700382 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800383 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 }
385
Prabir Pradhanedd96402022-02-15 01:46:16 -0800386 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
387 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700388 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800389 ASSERT_TRUE(pid.has_value());
390 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700391 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500392 }
393
Prabir Pradhanedd96402022-02-15 01:46:16 -0800394 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
395 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500396 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800397 ASSERT_TRUE(pid.has_value());
398 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500399 mNotifyAnr.notify_all();
400 }
401
402 void notifyNoFocusedWindowAnr(
403 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
404 std::scoped_lock lock(mLock);
405 mAnrApplications.push(applicationHandle);
406 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 }
408
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800409 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
410 std::scoped_lock lock(mLock);
411 mBrokenInputChannels.push(connectionToken);
412 mNotifyInputChannelBroken.notify_all();
413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700416
Chris Yef59a2f42020-10-16 12:55:26 -0700417 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
418 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
419 const std::vector<float>& values) override {}
420
421 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
422 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000423
Chris Yefb552902021-02-03 17:18:37 -0800424 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
425
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600426 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 *outConfig = mConfig;
428 }
429
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600430 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700431 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800432 switch (inputEvent->getType()) {
433 case AINPUT_EVENT_TYPE_KEY: {
434 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800435 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800436 break;
437 }
438
439 case AINPUT_EVENT_TYPE_MOTION: {
440 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800441 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800442 break;
443 }
444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 return true;
446 }
447
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800448 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
449 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
450 // Clear intercept state when we handled the event.
451 mInterceptKeyTimeout = 0ms;
452 }
453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600455 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600457 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800458 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
459 // Clear intercept state so we could dispatch the event in next wake.
460 mInterceptKeyTimeout = 0ms;
461 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 }
463
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600464 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 return false;
466 }
467
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600468 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
469 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700470 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
472 * essentially a passthrough for notifySwitch.
473 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800474 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 }
476
Sean Stoutb4e0a592021-02-23 07:34:53 -0800477 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600479 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700480 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700481 mOnPointerDownToken = newToken;
482 }
483
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000484 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000486 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800487 mPointerCaptureChangedCondition.notify_all();
488 }
489
arthurhungf452d0b2021-01-06 00:19:52 +0800490 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
491 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800492 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800493 mDropTargetWindowToken = token;
494 }
495
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700496 void assertFilterInputEventWasCalledInternal(
497 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700498 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800499 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700500 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800501 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503};
504
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505// --- InputDispatcherTest ---
506
507class InputDispatcherTest : public testing::Test {
508protected:
509 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700510 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000512 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800514 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800515 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000516 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700517 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 }
519
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000520 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700521 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700523 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700525
526 /**
527 * Used for debugging when writing the test
528 */
529 void dumpDispatcherState() {
530 std::string dump;
531 mDispatcher->dump(dump);
532 std::stringstream ss(dump);
533 std::string to;
534
535 while (std::getline(ss, to, '\n')) {
536 ALOGE("%s", to.c_str());
537 }
538 }
Vishnu Nair958da932020-08-21 17:12:37 -0700539
chaviw3277faf2021-05-19 16:45:23 -0500540 void setFocusedWindow(const sp<WindowInfoHandle>& window,
541 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700542 FocusRequest request;
543 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000544 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700545 if (focusedWindow) {
546 request.focusedToken = focusedWindow->getToken();
547 }
548 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
549 request.displayId = window->getInfo()->displayId;
550 mDispatcher->setFocusedWindow(request);
551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552};
553
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
555 KeyEvent event;
556
557 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800558 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
559 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600560 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
561 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800562 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000563 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
564 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 << "Should reject key events with undefined action.";
566
567 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800568 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
569 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600570 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800571 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000572 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
573 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 << "Should reject key events with ACTION_MULTIPLE.";
575}
576
577TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
578 MotionEvent event;
579 PointerProperties pointerProperties[MAX_POINTERS + 1];
580 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800581 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 pointerProperties[i].clear();
583 pointerProperties[i].id = i;
584 pointerCoords[i].clear();
585 }
586
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800587 // Some constants commonly used below
588 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
589 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
590 constexpr int32_t metaState = AMETA_NONE;
591 constexpr MotionClassification classification = MotionClassification::NONE;
592
chaviw9eaa22c2020-07-01 16:21:27 -0700593 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800595 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700596 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
597 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700598 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
599 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700600 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800601 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000602 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
603 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 << "Should reject motion events with undefined action.";
605
606 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800607 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800608 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
609 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
610 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
611 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500612 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800613 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000614 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
615 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 << "Should reject motion events with pointer down index too large.";
617
Garfield Tanfbe732e2020-01-24 11:26:14 -0800618 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700619 AMOTION_EVENT_ACTION_POINTER_DOWN |
620 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700621 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
622 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700623 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500624 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800625 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000626 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
627 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 << "Should reject motion events with pointer down index too small.";
629
630 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800631 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800632 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
633 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
634 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
635 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500636 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800637 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000638 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
639 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 << "Should reject motion events with pointer up index too large.";
641
Garfield Tanfbe732e2020-01-24 11:26:14 -0800642 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 AMOTION_EVENT_ACTION_POINTER_UP |
644 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700645 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
646 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700647 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500648 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800649 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000650 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
651 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 << "Should reject motion events with pointer up index too small.";
653
654 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800655 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
656 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700657 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700658 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
659 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800661 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000662 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
663 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 << "Should reject motion events with 0 pointers.";
665
Garfield Tanfbe732e2020-01-24 11:26:14 -0800666 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
667 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700668 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700669 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
670 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700671 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800672 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000673 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
674 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 << "Should reject motion events with more than MAX_POINTERS pointers.";
676
677 // Rejects motion events with invalid pointer ids.
678 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800679 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
680 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700681 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700682 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
683 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700684 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800685 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000686 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
687 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 << "Should reject motion events with pointer ids less than 0.";
689
690 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800691 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
692 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700693 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700694 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
695 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700696 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800697 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000698 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
699 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
701
702 // Rejects motion events with duplicate pointer ids.
703 pointerProperties[0].id = 1;
704 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800705 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
706 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700707 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700708 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
709 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700710 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800711 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000712 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
713 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 << "Should reject motion events with duplicate pointer ids.";
715}
716
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800717/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
718
719TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
720 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800721 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800722 mDispatcher->notifyConfigurationChanged(&args);
723 ASSERT_TRUE(mDispatcher->waitForIdle());
724
725 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
726}
727
728TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800729 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
730 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800731 mDispatcher->notifySwitch(&args);
732
733 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
734 args.policyFlags |= POLICY_FLAG_TRUSTED;
735 mFakePolicy->assertNotifySwitchWasCalled(args);
736}
737
Arthur Hungb92218b2018-08-14 12:00:21 +0800738// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700739static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700740// Default input dispatching timeout if there is no focused application or paused window
741// from which to determine an appropriate dispatching timeout.
742static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
743 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
744 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800745
746class FakeApplicationHandle : public InputApplicationHandle {
747public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700748 FakeApplicationHandle() {
749 mInfo.name = "Fake Application";
750 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500751 mInfo.dispatchingTimeoutMillis =
752 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700753 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800754 virtual ~FakeApplicationHandle() {}
755
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000756 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700757
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500758 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
759 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700760 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800761};
762
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800763class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800764public:
Garfield Tan15601662020-09-22 15:32:38 -0700765 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800766 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700767 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800768 }
769
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800770 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700771 InputEvent* event;
772 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
773 if (!consumeSeq) {
774 return nullptr;
775 }
776 finishEvent(*consumeSeq);
777 return event;
778 }
779
780 /**
781 * Receive an event without acknowledging it.
782 * Return the sequence number that could later be used to send finished signal.
783 */
784 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800785 uint32_t consumeSeq;
786 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800787
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800788 std::chrono::time_point start = std::chrono::steady_clock::now();
789 status_t status = WOULD_BLOCK;
790 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800791 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792 &event);
793 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
794 if (elapsed > 100ms) {
795 break;
796 }
797 }
798
799 if (status == WOULD_BLOCK) {
800 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700801 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800802 }
803
804 if (status != OK) {
805 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700806 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800807 }
808 if (event == nullptr) {
809 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700810 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800811 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700812 if (outEvent != nullptr) {
813 *outEvent = event;
814 }
815 return consumeSeq;
816 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800817
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700818 /**
819 * To be used together with "receiveEvent" to complete the consumption of an event.
820 */
821 void finishEvent(uint32_t consumeSeq) {
822 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
823 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800824 }
825
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000826 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
827 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
828 ASSERT_EQ(OK, status);
829 }
830
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000831 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
832 std::optional<int32_t> expectedDisplayId,
833 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800834 InputEvent* event = consume();
835
836 ASSERT_NE(nullptr, event) << mName.c_str()
837 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800838 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700839 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800840 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800841
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000842 if (expectedDisplayId.has_value()) {
843 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
844 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800845
Tiger Huang8664f8c2018-10-11 19:14:35 +0800846 switch (expectedEventType) {
847 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800848 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
849 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000850 if (expectedFlags.has_value()) {
851 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
852 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800853 break;
854 }
855 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800856 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000857 assertMotionAction(expectedAction, motionEvent.getAction());
858
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000859 if (expectedFlags.has_value()) {
860 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
861 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800862 break;
863 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100864 case AINPUT_EVENT_TYPE_FOCUS: {
865 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
866 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800867 case AINPUT_EVENT_TYPE_CAPTURE: {
868 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
869 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000870 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
871 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
872 }
arthurhungb89ccb02020-12-30 16:19:01 +0800873 case AINPUT_EVENT_TYPE_DRAG: {
874 FAIL() << "Use 'consumeDragEvent' for DRAG events";
875 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800876 default: {
877 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
878 }
879 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800880 }
881
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100882 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
883 InputEvent* event = consume();
884 ASSERT_NE(nullptr, event) << mName.c_str()
885 << ": consumer should have returned non-NULL event.";
886 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
887 << "Got " << inputEventTypeToString(event->getType())
888 << " event instead of FOCUS event";
889
890 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
891 << mName.c_str() << ": event displayId should always be NONE.";
892
893 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
894 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100895 }
896
Prabir Pradhan99987712020-11-10 18:43:05 -0800897 void consumeCaptureEvent(bool hasCapture) {
898 const InputEvent* event = consume();
899 ASSERT_NE(nullptr, event) << mName.c_str()
900 << ": consumer should have returned non-NULL event.";
901 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
902 << "Got " << inputEventTypeToString(event->getType())
903 << " event instead of CAPTURE event";
904
905 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
906 << mName.c_str() << ": event displayId should always be NONE.";
907
908 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
909 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
910 }
911
arthurhungb89ccb02020-12-30 16:19:01 +0800912 void consumeDragEvent(bool isExiting, float x, float y) {
913 const InputEvent* event = consume();
914 ASSERT_NE(nullptr, event) << mName.c_str()
915 << ": consumer should have returned non-NULL event.";
916 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
917 << "Got " << inputEventTypeToString(event->getType())
918 << " event instead of DRAG event";
919
920 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
921 << mName.c_str() << ": event displayId should always be NONE.";
922
923 const auto& dragEvent = static_cast<const DragEvent&>(*event);
924 EXPECT_EQ(isExiting, dragEvent.isExiting());
925 EXPECT_EQ(x, dragEvent.getX());
926 EXPECT_EQ(y, dragEvent.getY());
927 }
928
Antonio Kantekf16f2832021-09-28 04:39:20 +0000929 void consumeTouchModeEvent(bool inTouchMode) {
930 const InputEvent* event = consume();
931 ASSERT_NE(nullptr, event) << mName.c_str()
932 << ": consumer should have returned non-NULL event.";
933 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
934 << "Got " << inputEventTypeToString(event->getType())
935 << " event instead of TOUCH_MODE event";
936
937 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
938 << mName.c_str() << ": event displayId should always be NONE.";
939 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
940 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
941 }
942
chaviwd1c23182019-12-20 18:44:56 -0800943 void assertNoEvents() {
944 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 if (event == nullptr) {
946 return;
947 }
948 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
949 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
950 ADD_FAILURE() << "Received key event "
951 << KeyEvent::actionToString(keyEvent.getAction());
952 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
953 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
954 ADD_FAILURE() << "Received motion event "
955 << MotionEvent::actionToString(motionEvent.getAction());
956 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
957 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
958 ADD_FAILURE() << "Received focus event, hasFocus = "
959 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800960 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
961 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
962 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
963 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000964 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
965 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
966 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
967 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968 }
969 FAIL() << mName.c_str()
970 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800971 }
972
973 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
974
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800975 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
976
chaviwd1c23182019-12-20 18:44:56 -0800977protected:
978 std::unique_ptr<InputConsumer> mConsumer;
979 PreallocatedInputEventFactory mEventFactory;
980
981 std::string mName;
982};
983
chaviw3277faf2021-05-19 16:45:23 -0500984class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800985public:
986 static const int32_t WIDTH = 600;
987 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800988
Chris Yea209fde2020-07-22 13:54:51 -0700989 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700990 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500991 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800992 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500993 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700994 base::Result<std::unique_ptr<InputChannel>> channel =
995 dispatcher->createInputChannel(name);
996 token = (*channel)->getConnectionToken();
997 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800998 }
999
1000 inputApplicationHandle->updateInfo();
1001 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1002
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001003 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001004 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001005 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001006 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001007 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001008 mInfo.frameLeft = 0;
1009 mInfo.frameTop = 0;
1010 mInfo.frameRight = WIDTH;
1011 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001012 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001013 mInfo.globalScaleFactor = 1.0;
1014 mInfo.touchableRegion.clear();
1015 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001016 mInfo.ownerPid = WINDOW_PID;
1017 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001018 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001019 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001020 }
1021
Arthur Hungabbb9d82021-09-01 14:52:30 +00001022 sp<FakeWindowHandle> clone(
1023 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001024 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001025 sp<FakeWindowHandle> handle =
1026 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1027 displayId, mInfo.token);
1028 return handle;
1029 }
1030
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001031 void setTouchable(bool touchable) {
1032 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1033 }
chaviwd1c23182019-12-20 18:44:56 -08001034
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001035 void setFocusable(bool focusable) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1037 }
1038
1039 void setVisible(bool visible) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1041 }
Vishnu Nair958da932020-08-21 17:12:37 -07001042
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001043 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001044 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001045 }
1046
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001047 void setPaused(bool paused) {
1048 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1049 }
1050
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001051 void setPreventSplitting(bool preventSplitting) {
1052 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001053 }
1054
1055 void setSlippery(bool slippery) {
1056 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1057 }
1058
1059 void setWatchOutsideTouch(bool watchOutside) {
1060 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1061 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001062
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001063 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1064
1065 void setInterceptsStylus(bool interceptsStylus) {
1066 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1067 }
1068
1069 void setDropInput(bool dropInput) {
1070 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1071 }
1072
1073 void setDropInputIfObscured(bool dropInputIfObscured) {
1074 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1075 }
1076
1077 void setNoInputChannel(bool noInputChannel) {
1078 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1079 }
1080
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001081 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1082
chaviw3277faf2021-05-19 16:45:23 -05001083 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001084
Bernardo Rufino7393d172021-02-26 13:56:11 +00001085 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1086
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001087 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001088 mInfo.frameLeft = frame.left;
1089 mInfo.frameTop = frame.top;
1090 mInfo.frameRight = frame.right;
1091 mInfo.frameBottom = frame.bottom;
1092 mInfo.touchableRegion.clear();
1093 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001094
1095 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1096 ui::Transform translate;
1097 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1098 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001099 }
1100
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001101 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1102
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001103 void setIsWallpaper(bool isWallpaper) {
1104 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1105 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001106
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001107 void setDupTouchToWallpaper(bool hasWallpaper) {
1108 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1109 }
chaviwd1c23182019-12-20 18:44:56 -08001110
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001111 void setTrustedOverlay(bool trustedOverlay) {
1112 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1113 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001114
chaviw9eaa22c2020-07-01 16:21:27 -07001115 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1116 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1117 }
1118
1119 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001120
yunho.shinf4a80b82020-11-16 21:13:57 +09001121 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1122
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001123 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1124 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1125 expectedFlags);
1126 }
1127
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001128 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1129 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1130 }
1131
Svet Ganov5d3bc372020-01-26 23:11:07 -08001132 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001133 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001134 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1135 expectedFlags);
1136 }
1137
1138 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001139 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001140 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1141 expectedFlags);
1142 }
1143
1144 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001145 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001146 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1147 }
1148
1149 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1150 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001151 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1152 expectedFlags);
1153 }
1154
Svet Ganov5d3bc372020-01-26 23:11:07 -08001155 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001156 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1157 int32_t expectedFlags = 0) {
1158 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1159 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001160 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1161 }
1162
1163 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001164 int32_t expectedFlags = 0) {
1165 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1166 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001167 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1168 }
1169
1170 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001171 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001172 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1173 expectedFlags);
1174 }
1175
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001176 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1177 int32_t expectedFlags = 0) {
1178 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1179 expectedFlags);
1180 }
1181
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001182 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1183 int32_t expectedFlags = 0) {
1184 InputEvent* event = consume();
1185 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1186 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1187 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1188 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1189 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1190 }
1191
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001192 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1193 ASSERT_NE(mInputReceiver, nullptr)
1194 << "Cannot consume events from a window with no receiver";
1195 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1196 }
1197
Prabir Pradhan99987712020-11-10 18:43:05 -08001198 void consumeCaptureEvent(bool hasCapture) {
1199 ASSERT_NE(mInputReceiver, nullptr)
1200 << "Cannot consume events from a window with no receiver";
1201 mInputReceiver->consumeCaptureEvent(hasCapture);
1202 }
1203
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001204 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1205 std::optional<int32_t> expectedDisplayId,
1206 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001207 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1208 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1209 expectedFlags);
1210 }
1211
arthurhungb89ccb02020-12-30 16:19:01 +08001212 void consumeDragEvent(bool isExiting, float x, float y) {
1213 mInputReceiver->consumeDragEvent(isExiting, x, y);
1214 }
1215
Antonio Kantekf16f2832021-09-28 04:39:20 +00001216 void consumeTouchModeEvent(bool inTouchMode) {
1217 ASSERT_NE(mInputReceiver, nullptr)
1218 << "Cannot consume events from a window with no receiver";
1219 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1220 }
1221
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001222 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001223 if (mInputReceiver == nullptr) {
1224 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1225 return std::nullopt;
1226 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001227 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001228 }
1229
1230 void finishEvent(uint32_t sequenceNum) {
1231 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1232 mInputReceiver->finishEvent(sequenceNum);
1233 }
1234
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001235 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1236 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1237 mInputReceiver->sendTimeline(inputEventId, timeline);
1238 }
1239
chaviwaf87b3e2019-10-01 16:59:28 -07001240 InputEvent* consume() {
1241 if (mInputReceiver == nullptr) {
1242 return nullptr;
1243 }
1244 return mInputReceiver->consume();
1245 }
1246
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001247 MotionEvent* consumeMotion() {
1248 InputEvent* event = consume();
1249 if (event == nullptr) {
1250 ADD_FAILURE() << "Consume failed : no event";
1251 return nullptr;
1252 }
1253 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1254 ADD_FAILURE() << "Instead of motion event, got "
1255 << inputEventTypeToString(event->getType());
1256 return nullptr;
1257 }
1258 return static_cast<MotionEvent*>(event);
1259 }
1260
Arthur Hungb92218b2018-08-14 12:00:21 +08001261 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001262 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001263 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001264 return; // Can't receive events if the window does not have input channel
1265 }
1266 ASSERT_NE(nullptr, mInputReceiver)
1267 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001268 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001269 }
1270
chaviwaf87b3e2019-10-01 16:59:28 -07001271 sp<IBinder> getToken() { return mInfo.token; }
1272
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001273 const std::string& getName() { return mName; }
1274
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001275 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1276 mInfo.ownerPid = ownerPid;
1277 mInfo.ownerUid = ownerUid;
1278 }
1279
Prabir Pradhanedd96402022-02-15 01:46:16 -08001280 int32_t getPid() const { return mInfo.ownerPid; }
1281
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001282 void destroyReceiver() { mInputReceiver = nullptr; }
1283
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001284 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1285
chaviwd1c23182019-12-20 18:44:56 -08001286private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001287 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001288 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001289 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001290};
1291
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001292std::atomic<int32_t> FakeWindowHandle::sId{1};
1293
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001294static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001295 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001296 int32_t displayId = ADISPLAY_ID_NONE,
1297 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001298 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001299 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1300 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001301 KeyEvent event;
1302 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1303
1304 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001305 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001306 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1307 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001308
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001309 if (!allowKeyRepeat) {
1310 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1311 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001312 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001313 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001314}
1315
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001316static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001317 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001318 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1319}
1320
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001321// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1322// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1323// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001324static InputEventInjectionResult injectKeyDownNoRepeat(
1325 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001326 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1327 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1328 /* allowKeyRepeat */ false);
1329}
1330
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001331static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001332 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001333 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1334}
1335
Garfield Tandf26e862020-07-01 20:18:19 -07001336class PointerBuilder {
1337public:
1338 PointerBuilder(int32_t id, int32_t toolType) {
1339 mProperties.clear();
1340 mProperties.id = id;
1341 mProperties.toolType = toolType;
1342 mCoords.clear();
1343 }
1344
1345 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1346
1347 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1348
1349 PointerBuilder& axis(int32_t axis, float value) {
1350 mCoords.setAxisValue(axis, value);
1351 return *this;
1352 }
1353
1354 PointerProperties buildProperties() const { return mProperties; }
1355
1356 PointerCoords buildCoords() const { return mCoords; }
1357
1358private:
1359 PointerProperties mProperties;
1360 PointerCoords mCoords;
1361};
1362
1363class MotionEventBuilder {
1364public:
1365 MotionEventBuilder(int32_t action, int32_t source) {
1366 mAction = action;
1367 mSource = source;
1368 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1369 }
1370
1371 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1372 mEventTime = eventTime;
1373 return *this;
1374 }
1375
1376 MotionEventBuilder& displayId(int32_t displayId) {
1377 mDisplayId = displayId;
1378 return *this;
1379 }
1380
1381 MotionEventBuilder& actionButton(int32_t actionButton) {
1382 mActionButton = actionButton;
1383 return *this;
1384 }
1385
arthurhung6d4bed92021-03-17 11:59:33 +08001386 MotionEventBuilder& buttonState(int32_t buttonState) {
1387 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001388 return *this;
1389 }
1390
1391 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1392 mRawXCursorPosition = rawXCursorPosition;
1393 return *this;
1394 }
1395
1396 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1397 mRawYCursorPosition = rawYCursorPosition;
1398 return *this;
1399 }
1400
1401 MotionEventBuilder& pointer(PointerBuilder pointer) {
1402 mPointers.push_back(pointer);
1403 return *this;
1404 }
1405
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001406 MotionEventBuilder& addFlag(uint32_t flags) {
1407 mFlags |= flags;
1408 return *this;
1409 }
1410
Garfield Tandf26e862020-07-01 20:18:19 -07001411 MotionEvent build() {
1412 std::vector<PointerProperties> pointerProperties;
1413 std::vector<PointerCoords> pointerCoords;
1414 for (const PointerBuilder& pointer : mPointers) {
1415 pointerProperties.push_back(pointer.buildProperties());
1416 pointerCoords.push_back(pointer.buildCoords());
1417 }
1418
1419 // Set mouse cursor position for the most common cases to avoid boilerplate.
1420 if (mSource == AINPUT_SOURCE_MOUSE &&
1421 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1422 mPointers.size() == 1) {
1423 mRawXCursorPosition = pointerCoords[0].getX();
1424 mRawYCursorPosition = pointerCoords[0].getY();
1425 }
1426
1427 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001428 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001429 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001430 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001431 mButtonState, MotionClassification::NONE, identityTransform,
1432 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001433 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1434 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001435
1436 return event;
1437 }
1438
1439private:
1440 int32_t mAction;
1441 int32_t mSource;
1442 nsecs_t mEventTime;
1443 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1444 int32_t mActionButton{0};
1445 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001446 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001447 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1448 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1449
1450 std::vector<PointerBuilder> mPointers;
1451};
1452
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001453static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001454 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001455 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001456 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1457 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1458 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1459 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001460}
1461
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001462static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001463 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001464 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001465 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001466 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1467 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001468 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001469 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1470 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001471 MotionEvent event = MotionEventBuilder(action, source)
1472 .displayId(displayId)
1473 .eventTime(eventTime)
1474 .rawXCursorPosition(cursorPosition.x)
1475 .rawYCursorPosition(cursorPosition.y)
1476 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1477 .x(position.x)
1478 .y(position.y))
1479 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001480
1481 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001482 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1483 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001484}
1485
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001486static InputEventInjectionResult injectMotionDown(
1487 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1488 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001489 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001490}
1491
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001492static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001493 int32_t source, int32_t displayId,
1494 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001495 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001496}
1497
Jackal Guof9696682018-10-05 12:23:23 +08001498static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1499 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1500 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001501 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1502 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1503 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001504
1505 return args;
1506}
1507
chaviwd1c23182019-12-20 18:44:56 -08001508static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1509 const std::vector<PointF>& points) {
1510 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001511 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1512 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1513 }
1514
chaviwd1c23182019-12-20 18:44:56 -08001515 PointerProperties pointerProperties[pointerCount];
1516 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001517
chaviwd1c23182019-12-20 18:44:56 -08001518 for (size_t i = 0; i < pointerCount; i++) {
1519 pointerProperties[i].clear();
1520 pointerProperties[i].id = i;
1521 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001522
chaviwd1c23182019-12-20 18:44:56 -08001523 pointerCoords[i].clear();
1524 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1525 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1526 }
Jackal Guof9696682018-10-05 12:23:23 +08001527
1528 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1529 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001530 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001531 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1532 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001533 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1534 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001535 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1536 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001537
1538 return args;
1539}
1540
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001541static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1542 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1543}
1544
chaviwd1c23182019-12-20 18:44:56 -08001545static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1546 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1547}
1548
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001549static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1550 const PointerCaptureRequest& request) {
1551 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001552}
1553
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001554/**
1555 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1556 * broken channel.
1557 */
1558TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1559 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1560 sp<FakeWindowHandle> window =
1561 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1562 ADISPLAY_ID_DEFAULT);
1563
1564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1565
1566 // Window closes its channel, but the window remains.
1567 window->destroyReceiver();
1568 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1569}
1570
Arthur Hungb92218b2018-08-14 12:00:21 +08001571TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001572 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001573 sp<FakeWindowHandle> window =
1574 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001575
Arthur Hung72d8dc32020-03-28 00:48:39 +00001576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1578 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1579 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001580
1581 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001582 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001583}
1584
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001585TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1587 sp<FakeWindowHandle> window =
1588 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1589
1590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1591 // Inject a MotionEvent to an unknown display.
1592 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1593 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1595
1596 // Window should receive motion event.
1597 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1598}
1599
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001600/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001601 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001602 * This test serves as a sanity check for the next test, where setInputWindows is
1603 * called twice.
1604 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001605TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001606 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001607 sp<FakeWindowHandle> window =
1608 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1609 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001610
1611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001613 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1614 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001615 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001616
1617 // Window should receive motion event.
1618 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1619}
1620
1621/**
1622 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001623 */
1624TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001625 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001626 sp<FakeWindowHandle> window =
1627 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1628 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001629
1630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001633 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1634 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001635 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001636
1637 // Window should receive motion event.
1638 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1639}
1640
Arthur Hungb92218b2018-08-14 12:00:21 +08001641// The foreground window should receive the first touch down event.
1642TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001644 sp<FakeWindowHandle> windowTop =
1645 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1646 sp<FakeWindowHandle> windowSecond =
1647 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001648
Arthur Hung72d8dc32020-03-28 00:48:39 +00001649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1652 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001653
1654 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001655 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001656 windowSecond->assertNoEvents();
1657}
1658
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001659/**
1660 * Two windows: A top window, and a wallpaper behind the window.
1661 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1662 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001663 * 1. foregroundWindow <-- dup touch to wallpaper
1664 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001665 */
1666TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1667 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1668 sp<FakeWindowHandle> foregroundWindow =
1669 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001670 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001671 sp<FakeWindowHandle> wallpaperWindow =
1672 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001673 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001674 constexpr int expectedWallpaperFlags =
1675 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1676
1677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1679 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1680 {100, 200}))
1681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1682
1683 // Both foreground window and its wallpaper should receive the touch down
1684 foregroundWindow->consumeMotionDown();
1685 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1686
1687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1688 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1689 ADISPLAY_ID_DEFAULT, {110, 200}))
1690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1691
1692 foregroundWindow->consumeMotionMove();
1693 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1694
1695 // Now the foreground window goes away, but the wallpaper stays
1696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1697 foregroundWindow->consumeMotionCancel();
1698 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1699 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1700}
1701
1702/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001703 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1704 * with the following differences:
1705 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1706 * clean up the connection.
1707 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1708 * Ensure that there's no crash in the dispatcher.
1709 */
1710TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1712 sp<FakeWindowHandle> foregroundWindow =
1713 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001714 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001715 sp<FakeWindowHandle> wallpaperWindow =
1716 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001717 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001718 constexpr int expectedWallpaperFlags =
1719 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1720
1721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1724 {100, 200}))
1725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1726
1727 // Both foreground window and its wallpaper should receive the touch down
1728 foregroundWindow->consumeMotionDown();
1729 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1730
1731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1732 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1733 ADISPLAY_ID_DEFAULT, {110, 200}))
1734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1735
1736 foregroundWindow->consumeMotionMove();
1737 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1738
1739 // Wallpaper closes its channel, but the window remains.
1740 wallpaperWindow->destroyReceiver();
1741 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1742
1743 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1744 // is no longer valid.
1745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1746 foregroundWindow->consumeMotionCancel();
1747}
1748
1749/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001750 * A single window that receives touch (on top), and a wallpaper window underneath it.
1751 * The top window gets a multitouch gesture.
1752 * Ensure that wallpaper gets the same gesture.
1753 */
1754TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1756 sp<FakeWindowHandle> window =
1757 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001758 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001759
1760 sp<FakeWindowHandle> wallpaperWindow =
1761 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001762 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001763 constexpr int expectedWallpaperFlags =
1764 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1765
1766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1767
1768 // Touch down on top window
1769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1770 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1771 {100, 100}))
1772 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1773
1774 // Both top window and its wallpaper should receive the touch down
1775 window->consumeMotionDown();
1776 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1777
1778 // Second finger down on the top window
1779 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001780 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001781 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1782 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1783 .x(100)
1784 .y(100))
1785 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1786 .x(150)
1787 .y(150))
1788 .build();
1789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1790 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1791 InputEventInjectionSync::WAIT_FOR_RESULT))
1792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1793
1794 window->consumeMotionPointerDown(1 /* pointerIndex */);
1795 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1796 expectedWallpaperFlags);
1797 window->assertNoEvents();
1798 wallpaperWindow->assertNoEvents();
1799}
1800
1801/**
1802 * Two windows: a window on the left and window on the right.
1803 * A third window, wallpaper, is behind both windows, and spans both top windows.
1804 * The first touch down goes to the left window. A second pointer touches down on the right window.
1805 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1806 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1807 * ACTION_POINTER_DOWN(1).
1808 */
1809TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1811 sp<FakeWindowHandle> leftWindow =
1812 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1813 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001814 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001815
1816 sp<FakeWindowHandle> rightWindow =
1817 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1818 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001819 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001820
1821 sp<FakeWindowHandle> wallpaperWindow =
1822 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1823 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001824 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001825 constexpr int expectedWallpaperFlags =
1826 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1827
1828 mDispatcher->setInputWindows(
1829 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1830
1831 // Touch down on left window
1832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1833 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1834 {100, 100}))
1835 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1836
1837 // Both foreground window and its wallpaper should receive the touch down
1838 leftWindow->consumeMotionDown();
1839 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1840
1841 // Second finger down on the right window
1842 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001843 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001844 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1845 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1846 .x(100)
1847 .y(100))
1848 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1849 .x(300)
1850 .y(100))
1851 .build();
1852 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1853 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1854 InputEventInjectionSync::WAIT_FOR_RESULT))
1855 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1856
1857 leftWindow->consumeMotionMove();
1858 // Since the touch is split, right window gets ACTION_DOWN
1859 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1860 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1861 expectedWallpaperFlags);
1862
1863 // Now, leftWindow, which received the first finger, disappears.
1864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1865 leftWindow->consumeMotionCancel();
1866 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1867 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1868
1869 // The pointer that's still down on the right window moves, and goes to the right window only.
1870 // As far as the dispatcher's concerned though, both pointers are still present.
1871 const MotionEvent secondFingerMoveEvent =
1872 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1873 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1874 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1875 .x(100)
1876 .y(100))
1877 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1878 .x(310)
1879 .y(110))
1880 .build();
1881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1882 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1883 InputEventInjectionSync::WAIT_FOR_RESULT));
1884 rightWindow->consumeMotionMove();
1885
1886 leftWindow->assertNoEvents();
1887 rightWindow->assertNoEvents();
1888 wallpaperWindow->assertNoEvents();
1889}
1890
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001891/**
1892 * On the display, have a single window, and also an area where there's no window.
1893 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1894 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1895 */
1896TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1897 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1898 sp<FakeWindowHandle> window =
1899 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1900
1901 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1902 NotifyMotionArgs args;
1903
1904 // Touch down on the empty space
1905 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1906
1907 mDispatcher->waitForIdle();
1908 window->assertNoEvents();
1909
1910 // Now touch down on the window with another pointer
1911 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1912 mDispatcher->waitForIdle();
1913 window->consumeMotionDown();
1914}
1915
1916/**
1917 * Same test as above, but instead of touching the empty space, the first touch goes to
1918 * non-touchable window.
1919 */
1920TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1921 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1922 sp<FakeWindowHandle> window1 =
1923 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1924 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1925 window1->setTouchable(false);
1926 sp<FakeWindowHandle> window2 =
1927 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1928 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1929
1930 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1931
1932 NotifyMotionArgs args;
1933 // Touch down on the non-touchable window
1934 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1935
1936 mDispatcher->waitForIdle();
1937 window1->assertNoEvents();
1938 window2->assertNoEvents();
1939
1940 // Now touch down on the window with another pointer
1941 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1942 mDispatcher->waitForIdle();
1943 window2->consumeMotionDown();
1944}
1945
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001946/**
1947 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
1948 * to the event time of the first ACTION_DOWN sent to the particular window.
1949 */
1950TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
1951 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1952 sp<FakeWindowHandle> window1 =
1953 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1954 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1955 sp<FakeWindowHandle> window2 =
1956 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1957 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1958
1959 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1960
1961 NotifyMotionArgs args;
1962 // Touch down on the first window
1963 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1964
1965 mDispatcher->waitForIdle();
1966 InputEvent* inputEvent1 = window1->consume();
1967 window2->assertNoEvents();
1968 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
1969 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
1970 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
1971
1972 // Now touch down on the window with another pointer
1973 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1974 mDispatcher->waitForIdle();
1975 InputEvent* inputEvent2 = window2->consume();
1976 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
1977 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
1978 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
1979 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
1980
1981 // Now move the pointer on the second window
1982 mDispatcher->notifyMotion(
1983 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
1984 mDispatcher->waitForIdle();
1985 InputEvent* inputEvent3 = window2->consume();
1986 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
1987 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
1988
1989 // Now add new touch down on the second window
1990 mDispatcher->notifyMotion(
1991 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
1992 mDispatcher->waitForIdle();
1993 InputEvent* inputEvent4 = window2->consume();
1994 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
1995 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
1996
1997 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
1998 window1->consumeMotionMove();
1999 window1->assertNoEvents();
2000
2001 // Now move the pointer on the first window
2002 mDispatcher->notifyMotion(
2003 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2004 mDispatcher->waitForIdle();
2005 InputEvent* inputEvent5 = window1->consume();
2006 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2007 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2008
2009 mDispatcher->notifyMotion(&(
2010 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2011 mDispatcher->waitForIdle();
2012 InputEvent* inputEvent6 = window1->consume();
2013 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2014 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2015}
2016
Garfield Tandf26e862020-07-01 20:18:19 -07002017TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002019 sp<FakeWindowHandle> windowLeft =
2020 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2021 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002022 sp<FakeWindowHandle> windowRight =
2023 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2024 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002025
2026 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2027
2028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2029
2030 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002032 injectMotionEvent(mDispatcher,
2033 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2034 AINPUT_SOURCE_MOUSE)
2035 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2036 .x(900)
2037 .y(400))
2038 .build()));
2039 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2040 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2041 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2042 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2043
2044 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002046 injectMotionEvent(mDispatcher,
2047 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2048 AINPUT_SOURCE_MOUSE)
2049 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2050 .x(300)
2051 .y(400))
2052 .build()));
2053 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2054 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2055 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2056 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2057 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2058 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2059
2060 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002062 injectMotionEvent(mDispatcher,
2063 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2064 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2065 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2066 .x(300)
2067 .y(400))
2068 .build()));
2069 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2070
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002072 injectMotionEvent(mDispatcher,
2073 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2074 AINPUT_SOURCE_MOUSE)
2075 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2076 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2077 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2078 .x(300)
2079 .y(400))
2080 .build()));
2081 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2082 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2083
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002085 injectMotionEvent(mDispatcher,
2086 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2087 AINPUT_SOURCE_MOUSE)
2088 .buttonState(0)
2089 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2090 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2091 .x(300)
2092 .y(400))
2093 .build()));
2094 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2095 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2096
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002098 injectMotionEvent(mDispatcher,
2099 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2100 .buttonState(0)
2101 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2102 .x(300)
2103 .y(400))
2104 .build()));
2105 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2106
2107 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002109 injectMotionEvent(mDispatcher,
2110 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2111 AINPUT_SOURCE_MOUSE)
2112 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2113 .x(900)
2114 .y(400))
2115 .build()));
2116 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2117 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2118 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2119 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2120 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2121 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2122}
2123
2124// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2125// directly in this test.
2126TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002127 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002128 sp<FakeWindowHandle> window =
2129 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2130 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002131
2132 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2133
2134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2135
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002137 injectMotionEvent(mDispatcher,
2138 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2139 AINPUT_SOURCE_MOUSE)
2140 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2141 .x(300)
2142 .y(400))
2143 .build()));
2144 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2145 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2146
2147 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002149 injectMotionEvent(mDispatcher,
2150 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2151 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2152 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2153 .x(300)
2154 .y(400))
2155 .build()));
2156 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2157
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002159 injectMotionEvent(mDispatcher,
2160 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2161 AINPUT_SOURCE_MOUSE)
2162 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2163 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2164 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2165 .x(300)
2166 .y(400))
2167 .build()));
2168 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2169 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2170
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002171 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002172 injectMotionEvent(mDispatcher,
2173 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2174 AINPUT_SOURCE_MOUSE)
2175 .buttonState(0)
2176 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2177 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2178 .x(300)
2179 .y(400))
2180 .build()));
2181 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2182 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2183
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002185 injectMotionEvent(mDispatcher,
2186 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2187 .buttonState(0)
2188 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2189 .x(300)
2190 .y(400))
2191 .build()));
2192 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2193
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002195 injectMotionEvent(mDispatcher,
2196 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2197 AINPUT_SOURCE_MOUSE)
2198 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2199 .x(300)
2200 .y(400))
2201 .build()));
2202 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2203 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2204}
2205
Garfield Tan00f511d2019-06-12 16:55:40 -07002206TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002207 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002208
2209 sp<FakeWindowHandle> windowLeft =
2210 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2211 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002212 sp<FakeWindowHandle> windowRight =
2213 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2214 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002215
2216 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2217
Arthur Hung72d8dc32020-03-28 00:48:39 +00002218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002219
2220 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2221 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002223 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002224 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002225 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002226 windowRight->assertNoEvents();
2227}
2228
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002229TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002230 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002231 sp<FakeWindowHandle> window =
2232 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002233 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002234
Arthur Hung72d8dc32020-03-28 00:48:39 +00002235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002236 setFocusedWindow(window);
2237
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002238 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002239
2240 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2241 mDispatcher->notifyKey(&keyArgs);
2242
2243 // Window should receive key down event.
2244 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2245
2246 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2247 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002248 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002249 mDispatcher->notifyDeviceReset(&args);
2250 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2251 AKEY_EVENT_FLAG_CANCELED);
2252}
2253
2254TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002255 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002256 sp<FakeWindowHandle> window =
2257 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2258
Arthur Hung72d8dc32020-03-28 00:48:39 +00002259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002260
2261 NotifyMotionArgs motionArgs =
2262 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2263 ADISPLAY_ID_DEFAULT);
2264 mDispatcher->notifyMotion(&motionArgs);
2265
2266 // Window should receive motion down event.
2267 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2268
2269 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2270 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002271 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002272 mDispatcher->notifyDeviceReset(&args);
2273 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2274 0 /*expectedFlags*/);
2275}
2276
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002277TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2278 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2279 sp<FakeWindowHandle> window =
2280 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2281 window->setFocusable(true);
2282
2283 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2284 setFocusedWindow(window);
2285
2286 window->consumeFocusEvent(true);
2287
2288 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2289 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2290 const nsecs_t injectTime = keyArgs.eventTime;
2291 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2292 mDispatcher->notifyKey(&keyArgs);
2293 // The dispatching time should be always greater than or equal to intercept key timeout.
2294 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2295 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2296 std::chrono::nanoseconds(interceptKeyTimeout).count());
2297}
2298
2299TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2300 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2301 sp<FakeWindowHandle> window =
2302 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2303 window->setFocusable(true);
2304
2305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2306 setFocusedWindow(window);
2307
2308 window->consumeFocusEvent(true);
2309
2310 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2311 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2312 mFakePolicy->setInterceptKeyTimeout(150ms);
2313 mDispatcher->notifyKey(&keyDown);
2314 mDispatcher->notifyKey(&keyUp);
2315
2316 // Window should receive key event immediately when same key up.
2317 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2318 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2319}
2320
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002321/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002322 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2323 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2324 * ACTION_OUTSIDE event is sent per gesture.
2325 */
2326TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2327 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2329 sp<FakeWindowHandle> window =
2330 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2331 window->setWatchOutsideTouch(true);
2332 window->setFrame(Rect{0, 0, 100, 100});
2333 sp<FakeWindowHandle> secondWindow =
2334 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2335 secondWindow->setFrame(Rect{100, 100, 200, 200});
2336 sp<FakeWindowHandle> thirdWindow =
2337 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2338 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2340
2341 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2342 NotifyMotionArgs motionArgs =
2343 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2344 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2345 mDispatcher->notifyMotion(&motionArgs);
2346 window->assertNoEvents();
2347 secondWindow->assertNoEvents();
2348
2349 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2350 // Now, `window` should get ACTION_OUTSIDE.
2351 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2352 {PointF{-10, -10}, PointF{105, 105}});
2353 mDispatcher->notifyMotion(&motionArgs);
2354 window->consumeMotionOutside();
2355 secondWindow->consumeMotionDown();
2356 thirdWindow->assertNoEvents();
2357
2358 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2359 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2360 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2361 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2362 mDispatcher->notifyMotion(&motionArgs);
2363 window->assertNoEvents();
2364 secondWindow->consumeMotionMove();
2365 thirdWindow->consumeMotionDown();
2366}
2367
2368/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002369 * Ensure the correct coordinate spaces are used by InputDispatcher.
2370 *
2371 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2372 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2373 * space.
2374 */
2375class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2376public:
2377 void SetUp() override {
2378 InputDispatcherTest::SetUp();
2379 mDisplayInfos.clear();
2380 mWindowInfos.clear();
2381 }
2382
2383 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2384 gui::DisplayInfo info;
2385 info.displayId = displayId;
2386 info.transform = transform;
2387 mDisplayInfos.push_back(std::move(info));
2388 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2389 }
2390
2391 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2392 mWindowInfos.push_back(*windowHandle->getInfo());
2393 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2394 }
2395
2396 // Set up a test scenario where the display has a scaled projection and there are two windows
2397 // on the display.
2398 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2399 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2400 // respectively.
2401 ui::Transform displayTransform;
2402 displayTransform.set(2, 0, 0, 4);
2403 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2404
2405 std::shared_ptr<FakeApplicationHandle> application =
2406 std::make_shared<FakeApplicationHandle>();
2407
2408 // Add two windows to the display. Their frames are represented in the display space.
2409 sp<FakeWindowHandle> firstWindow =
2410 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002411 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2412 addWindow(firstWindow);
2413
2414 sp<FakeWindowHandle> secondWindow =
2415 new FakeWindowHandle(application, mDispatcher, "Second Window",
2416 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002417 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2418 addWindow(secondWindow);
2419 return {std::move(firstWindow), std::move(secondWindow)};
2420 }
2421
2422private:
2423 std::vector<gui::DisplayInfo> mDisplayInfos;
2424 std::vector<gui::WindowInfo> mWindowInfos;
2425};
2426
2427TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2428 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2429 // Send down to the first window. The point is represented in the display space. The point is
2430 // selected so that if the hit test was done with the transform applied to it, then it would
2431 // end up in the incorrect window.
2432 NotifyMotionArgs downMotionArgs =
2433 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2434 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2435 mDispatcher->notifyMotion(&downMotionArgs);
2436
2437 firstWindow->consumeMotionDown();
2438 secondWindow->assertNoEvents();
2439}
2440
2441// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2442// the event should be treated as being in the logical display space.
2443TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2444 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2445 // Send down to the first window. The point is represented in the logical display space. The
2446 // point is selected so that if the hit test was done in logical display space, then it would
2447 // end up in the incorrect window.
2448 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2449 PointF{75 * 2, 55 * 4});
2450
2451 firstWindow->consumeMotionDown();
2452 secondWindow->assertNoEvents();
2453}
2454
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002455// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2456// event should be treated as being in the logical display space.
2457TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2458 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2459
2460 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2461 ui::Transform injectedEventTransform;
2462 injectedEventTransform.set(matrix);
2463 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2464 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2465
2466 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2467 .displayId(ADISPLAY_ID_DEFAULT)
2468 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2469 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2470 .x(untransformedPoint.x)
2471 .y(untransformedPoint.y))
2472 .build();
2473 event.transform(matrix);
2474
2475 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2476 InputEventInjectionSync::WAIT_FOR_RESULT);
2477
2478 firstWindow->consumeMotionDown();
2479 secondWindow->assertNoEvents();
2480}
2481
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002482TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2483 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2484
2485 // Send down to the second window.
2486 NotifyMotionArgs downMotionArgs =
2487 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2488 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2489 mDispatcher->notifyMotion(&downMotionArgs);
2490
2491 firstWindow->assertNoEvents();
2492 const MotionEvent* event = secondWindow->consumeMotion();
2493 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2494
2495 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2496 EXPECT_EQ(300, event->getRawX(0));
2497 EXPECT_EQ(880, event->getRawY(0));
2498
2499 // Ensure that the x and y values are in the window's coordinate space.
2500 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2501 // the logical display space. This will be the origin of the window space.
2502 EXPECT_EQ(100, event->getX(0));
2503 EXPECT_EQ(80, event->getY(0));
2504}
2505
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002506using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2507 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002508
2509class TransferTouchFixture : public InputDispatcherTest,
2510 public ::testing::WithParamInterface<TransferFunction> {};
2511
2512TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002514
2515 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002516 sp<FakeWindowHandle> firstWindow =
2517 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2518 sp<FakeWindowHandle> secondWindow =
2519 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002520
2521 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002522 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002523
2524 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002525 NotifyMotionArgs downMotionArgs =
2526 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2527 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002528 mDispatcher->notifyMotion(&downMotionArgs);
2529 // Only the first window should get the down event
2530 firstWindow->consumeMotionDown();
2531 secondWindow->assertNoEvents();
2532
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002533 // Transfer touch to the second window
2534 TransferFunction f = GetParam();
2535 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2536 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002537 // The first window gets cancel and the second gets down
2538 firstWindow->consumeMotionCancel();
2539 secondWindow->consumeMotionDown();
2540
2541 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002542 NotifyMotionArgs upMotionArgs =
2543 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2544 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002545 mDispatcher->notifyMotion(&upMotionArgs);
2546 // The first window gets no events and the second gets up
2547 firstWindow->assertNoEvents();
2548 secondWindow->consumeMotionUp();
2549}
2550
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002551/**
2552 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2553 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2554 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2555 * natural to the user.
2556 * In this test, we are sending a pointer to both spy window and first window. We then try to
2557 * transfer touch to the second window. The dispatcher should identify the first window as the
2558 * one that should lose the gesture, and therefore the action should be to move the gesture from
2559 * the first window to the second.
2560 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2561 * the other API, as well.
2562 */
2563TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2565
2566 // Create a couple of windows + a spy window
2567 sp<FakeWindowHandle> spyWindow =
2568 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2569 spyWindow->setTrustedOverlay(true);
2570 spyWindow->setSpy(true);
2571 sp<FakeWindowHandle> firstWindow =
2572 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2573 sp<FakeWindowHandle> secondWindow =
2574 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2575
2576 // Add the windows to the dispatcher
2577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2578
2579 // Send down to the first window
2580 NotifyMotionArgs downMotionArgs =
2581 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2582 ADISPLAY_ID_DEFAULT);
2583 mDispatcher->notifyMotion(&downMotionArgs);
2584 // Only the first window and spy should get the down event
2585 spyWindow->consumeMotionDown();
2586 firstWindow->consumeMotionDown();
2587
2588 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2589 // if f === 'transferTouch'.
2590 TransferFunction f = GetParam();
2591 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2592 ASSERT_TRUE(success);
2593 // The first window gets cancel and the second gets down
2594 firstWindow->consumeMotionCancel();
2595 secondWindow->consumeMotionDown();
2596
2597 // Send up event to the second window
2598 NotifyMotionArgs upMotionArgs =
2599 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2600 ADISPLAY_ID_DEFAULT);
2601 mDispatcher->notifyMotion(&upMotionArgs);
2602 // The first window gets no events and the second+spy get up
2603 firstWindow->assertNoEvents();
2604 spyWindow->consumeMotionUp();
2605 secondWindow->consumeMotionUp();
2606}
2607
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002608TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002609 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002610
2611 PointF touchPoint = {10, 10};
2612
2613 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002614 sp<FakeWindowHandle> firstWindow =
2615 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002616 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002617 sp<FakeWindowHandle> secondWindow =
2618 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002619 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002620
2621 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002623
2624 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002625 NotifyMotionArgs downMotionArgs =
2626 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2627 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002628 mDispatcher->notifyMotion(&downMotionArgs);
2629 // Only the first window should get the down event
2630 firstWindow->consumeMotionDown();
2631 secondWindow->assertNoEvents();
2632
2633 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002634 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002635 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002636 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002637 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2638 // Only the first window should get the pointer down event
2639 firstWindow->consumeMotionPointerDown(1);
2640 secondWindow->assertNoEvents();
2641
2642 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002643 TransferFunction f = GetParam();
2644 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2645 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002646 // The first window gets cancel and the second gets down and pointer down
2647 firstWindow->consumeMotionCancel();
2648 secondWindow->consumeMotionDown();
2649 secondWindow->consumeMotionPointerDown(1);
2650
2651 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002652 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002653 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002654 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002655 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2656 // The first window gets nothing and the second gets pointer up
2657 firstWindow->assertNoEvents();
2658 secondWindow->consumeMotionPointerUp(1);
2659
2660 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002661 NotifyMotionArgs upMotionArgs =
2662 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2663 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002664 mDispatcher->notifyMotion(&upMotionArgs);
2665 // The first window gets nothing and the second gets up
2666 firstWindow->assertNoEvents();
2667 secondWindow->consumeMotionUp();
2668}
2669
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002670// For the cases of single pointer touch and two pointers non-split touch, the api's
2671// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2672// for the case where there are multiple pointers split across several windows.
2673INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2674 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002675 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2676 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002677 return dispatcher->transferTouch(destChannelToken,
2678 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002679 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002680 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2681 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002682 return dispatcher->transferTouchFocus(from, to,
2683 false /*isDragAndDrop*/);
2684 }));
2685
Svet Ganov5d3bc372020-01-26 23:11:07 -08002686TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002687 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002688
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002689 sp<FakeWindowHandle> firstWindow =
2690 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002691 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002692
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002693 sp<FakeWindowHandle> secondWindow =
2694 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002695 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002696
2697 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002699
2700 PointF pointInFirst = {300, 200};
2701 PointF pointInSecond = {300, 600};
2702
2703 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002704 NotifyMotionArgs firstDownMotionArgs =
2705 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2706 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002707 mDispatcher->notifyMotion(&firstDownMotionArgs);
2708 // Only the first window should get the down event
2709 firstWindow->consumeMotionDown();
2710 secondWindow->assertNoEvents();
2711
2712 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002713 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002714 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002715 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002716 mDispatcher->notifyMotion(&secondDownMotionArgs);
2717 // The first window gets a move and the second a down
2718 firstWindow->consumeMotionMove();
2719 secondWindow->consumeMotionDown();
2720
2721 // Transfer touch focus to the second window
2722 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2723 // The first window gets cancel and the new gets pointer down (it already saw down)
2724 firstWindow->consumeMotionCancel();
2725 secondWindow->consumeMotionPointerDown(1);
2726
2727 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002728 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002729 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002730 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002731 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2732 // The first window gets nothing and the second gets pointer up
2733 firstWindow->assertNoEvents();
2734 secondWindow->consumeMotionPointerUp(1);
2735
2736 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002737 NotifyMotionArgs upMotionArgs =
2738 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2739 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002740 mDispatcher->notifyMotion(&upMotionArgs);
2741 // The first window gets nothing and the second gets up
2742 firstWindow->assertNoEvents();
2743 secondWindow->consumeMotionUp();
2744}
2745
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002746// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2747// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2748// touch is not supported, so the touch should continue on those windows and the transferred-to
2749// window should get nothing.
2750TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2751 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2752
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002753 sp<FakeWindowHandle> firstWindow =
2754 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2755 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002756
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002757 sp<FakeWindowHandle> secondWindow =
2758 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2759 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002760
2761 // Add the windows to the dispatcher
2762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2763
2764 PointF pointInFirst = {300, 200};
2765 PointF pointInSecond = {300, 600};
2766
2767 // Send down to the first window
2768 NotifyMotionArgs firstDownMotionArgs =
2769 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2770 ADISPLAY_ID_DEFAULT, {pointInFirst});
2771 mDispatcher->notifyMotion(&firstDownMotionArgs);
2772 // Only the first window should get the down event
2773 firstWindow->consumeMotionDown();
2774 secondWindow->assertNoEvents();
2775
2776 // Send down to the second window
2777 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002778 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002779 {pointInFirst, pointInSecond});
2780 mDispatcher->notifyMotion(&secondDownMotionArgs);
2781 // The first window gets a move and the second a down
2782 firstWindow->consumeMotionMove();
2783 secondWindow->consumeMotionDown();
2784
2785 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002786 const bool transferred =
2787 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002788 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2789 ASSERT_FALSE(transferred);
2790 firstWindow->assertNoEvents();
2791 secondWindow->assertNoEvents();
2792
2793 // The rest of the dispatch should proceed as normal
2794 // Send pointer up to the second window
2795 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002796 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002797 {pointInFirst, pointInSecond});
2798 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2799 // The first window gets MOVE and the second gets pointer up
2800 firstWindow->consumeMotionMove();
2801 secondWindow->consumeMotionUp();
2802
2803 // Send up event to the first window
2804 NotifyMotionArgs upMotionArgs =
2805 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2806 ADISPLAY_ID_DEFAULT);
2807 mDispatcher->notifyMotion(&upMotionArgs);
2808 // The first window gets nothing and the second gets up
2809 firstWindow->consumeMotionUp();
2810 secondWindow->assertNoEvents();
2811}
2812
Arthur Hungabbb9d82021-09-01 14:52:30 +00002813// This case will create two windows and one mirrored window on the default display and mirror
2814// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2815// the windows info of second display before default display.
2816TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2817 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2818 sp<FakeWindowHandle> firstWindowInPrimary =
2819 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2820 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002821 sp<FakeWindowHandle> secondWindowInPrimary =
2822 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2823 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002824
2825 sp<FakeWindowHandle> mirrorWindowInPrimary =
2826 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2827 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002828
2829 sp<FakeWindowHandle> firstWindowInSecondary =
2830 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2831 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002832
2833 sp<FakeWindowHandle> secondWindowInSecondary =
2834 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2835 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002836
2837 // Update window info, let it find window handle of second display first.
2838 mDispatcher->setInputWindows(
2839 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2840 {ADISPLAY_ID_DEFAULT,
2841 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2842
2843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2845 {50, 50}))
2846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2847
2848 // Window should receive motion event.
2849 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2850
2851 // Transfer touch focus
2852 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2853 secondWindowInPrimary->getToken()));
2854 // The first window gets cancel.
2855 firstWindowInPrimary->consumeMotionCancel();
2856 secondWindowInPrimary->consumeMotionDown();
2857
2858 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2859 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2860 ADISPLAY_ID_DEFAULT, {150, 50}))
2861 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2862 firstWindowInPrimary->assertNoEvents();
2863 secondWindowInPrimary->consumeMotionMove();
2864
2865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2866 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2867 {150, 50}))
2868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2869 firstWindowInPrimary->assertNoEvents();
2870 secondWindowInPrimary->consumeMotionUp();
2871}
2872
2873// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2874// 'transferTouch' api.
2875TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2876 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2877 sp<FakeWindowHandle> firstWindowInPrimary =
2878 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2879 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002880 sp<FakeWindowHandle> secondWindowInPrimary =
2881 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2882 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002883
2884 sp<FakeWindowHandle> mirrorWindowInPrimary =
2885 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2886 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002887
2888 sp<FakeWindowHandle> firstWindowInSecondary =
2889 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2890 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002891
2892 sp<FakeWindowHandle> secondWindowInSecondary =
2893 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2894 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002895
2896 // Update window info, let it find window handle of second display first.
2897 mDispatcher->setInputWindows(
2898 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2899 {ADISPLAY_ID_DEFAULT,
2900 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2901
2902 // Touch on second display.
2903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2904 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2905 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2906
2907 // Window should receive motion event.
2908 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2909
2910 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002911 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002912
2913 // The first window gets cancel.
2914 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2915 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2916
2917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2918 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2919 SECOND_DISPLAY_ID, {150, 50}))
2920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2921 firstWindowInPrimary->assertNoEvents();
2922 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2923
2924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2925 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2926 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2927 firstWindowInPrimary->assertNoEvents();
2928 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2929}
2930
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002931TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002932 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002933 sp<FakeWindowHandle> window =
2934 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2935
Vishnu Nair47074b82020-08-14 11:54:47 -07002936 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002938 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002939
2940 window->consumeFocusEvent(true);
2941
2942 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2943 mDispatcher->notifyKey(&keyArgs);
2944
2945 // Window should receive key down event.
2946 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2947}
2948
2949TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002950 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002951 sp<FakeWindowHandle> window =
2952 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2953
Arthur Hung72d8dc32020-03-28 00:48:39 +00002954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002955
2956 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2957 mDispatcher->notifyKey(&keyArgs);
2958 mDispatcher->waitForIdle();
2959
2960 window->assertNoEvents();
2961}
2962
2963// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2964TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002965 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002966 sp<FakeWindowHandle> window =
2967 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2968
Arthur Hung72d8dc32020-03-28 00:48:39 +00002969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002970
2971 // Send key
2972 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2973 mDispatcher->notifyKey(&keyArgs);
2974 // Send motion
2975 NotifyMotionArgs motionArgs =
2976 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2977 ADISPLAY_ID_DEFAULT);
2978 mDispatcher->notifyMotion(&motionArgs);
2979
2980 // Window should receive only the motion event
2981 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2982 window->assertNoEvents(); // Key event or focus event will not be received
2983}
2984
arthurhungea3f4fc2020-12-21 23:18:53 +08002985TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2986 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2987
arthurhungea3f4fc2020-12-21 23:18:53 +08002988 sp<FakeWindowHandle> firstWindow =
2989 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2990 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002991
arthurhungea3f4fc2020-12-21 23:18:53 +08002992 sp<FakeWindowHandle> secondWindow =
2993 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2994 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002995
2996 // Add the windows to the dispatcher
2997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2998
2999 PointF pointInFirst = {300, 200};
3000 PointF pointInSecond = {300, 600};
3001
3002 // Send down to the first window
3003 NotifyMotionArgs firstDownMotionArgs =
3004 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3005 ADISPLAY_ID_DEFAULT, {pointInFirst});
3006 mDispatcher->notifyMotion(&firstDownMotionArgs);
3007 // Only the first window should get the down event
3008 firstWindow->consumeMotionDown();
3009 secondWindow->assertNoEvents();
3010
3011 // Send down to the second window
3012 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003013 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003014 {pointInFirst, pointInSecond});
3015 mDispatcher->notifyMotion(&secondDownMotionArgs);
3016 // The first window gets a move and the second a down
3017 firstWindow->consumeMotionMove();
3018 secondWindow->consumeMotionDown();
3019
3020 // Send pointer cancel to the second window
3021 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003022 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003023 {pointInFirst, pointInSecond});
3024 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3025 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3026 // The first window gets move and the second gets cancel.
3027 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3028 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3029
3030 // Send up event.
3031 NotifyMotionArgs upMotionArgs =
3032 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3033 ADISPLAY_ID_DEFAULT);
3034 mDispatcher->notifyMotion(&upMotionArgs);
3035 // The first window gets up and the second gets nothing.
3036 firstWindow->consumeMotionUp();
3037 secondWindow->assertNoEvents();
3038}
3039
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003040TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3041 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3042
3043 sp<FakeWindowHandle> window =
3044 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3046 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3047 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3048 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3049
3050 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3051 window->assertNoEvents();
3052 mDispatcher->waitForIdle();
3053}
3054
chaviwd1c23182019-12-20 18:44:56 -08003055class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003056public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003057 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003058 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003059 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003060 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003061 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003062 }
3063
chaviwd1c23182019-12-20 18:44:56 -08003064 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3065
3066 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3067 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3068 expectedDisplayId, expectedFlags);
3069 }
3070
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003071 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3072
3073 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3074
chaviwd1c23182019-12-20 18:44:56 -08003075 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3076 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3077 expectedDisplayId, expectedFlags);
3078 }
3079
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003080 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3081 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3082 expectedDisplayId, expectedFlags);
3083 }
3084
chaviwd1c23182019-12-20 18:44:56 -08003085 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3086 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3087 expectedDisplayId, expectedFlags);
3088 }
3089
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003090 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3091 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3092 expectedDisplayId, expectedFlags);
3093 }
3094
Arthur Hungfbfa5722021-11-16 02:45:54 +00003095 void consumeMotionPointerDown(int32_t pointerIdx) {
3096 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3097 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3098 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3099 0 /*expectedFlags*/);
3100 }
3101
Evan Rosky84f07f02021-04-16 10:42:42 -07003102 MotionEvent* consumeMotion() {
3103 InputEvent* event = mInputReceiver->consume();
3104 if (!event) {
3105 ADD_FAILURE() << "No event was produced";
3106 return nullptr;
3107 }
3108 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3109 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3110 return nullptr;
3111 }
3112 return static_cast<MotionEvent*>(event);
3113 }
3114
chaviwd1c23182019-12-20 18:44:56 -08003115 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3116
3117private:
3118 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003119};
3120
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003121using InputDispatcherMonitorTest = InputDispatcherTest;
3122
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003123/**
3124 * Two entities that receive touch: A window, and a global monitor.
3125 * The touch goes to the window, and then the window disappears.
3126 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3127 * for the monitor, as well.
3128 * 1. foregroundWindow
3129 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3130 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003131TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003132 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3133 sp<FakeWindowHandle> window =
3134 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3135
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003136 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003137
3138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3140 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3141 {100, 200}))
3142 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3143
3144 // Both the foreground window and the global monitor should receive the touch down
3145 window->consumeMotionDown();
3146 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3147
3148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3149 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3150 ADISPLAY_ID_DEFAULT, {110, 200}))
3151 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3152
3153 window->consumeMotionMove();
3154 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3155
3156 // Now the foreground window goes away
3157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3158 window->consumeMotionCancel();
3159 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3160
3161 // If more events come in, there will be no more foreground window to send them to. This will
3162 // cause a cancel for the monitor, as well.
3163 ASSERT_EQ(InputEventInjectionResult::FAILED,
3164 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3165 ADISPLAY_ID_DEFAULT, {120, 200}))
3166 << "Injection should fail because the window was removed";
3167 window->assertNoEvents();
3168 // Global monitor now gets the cancel
3169 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3170}
3171
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003172TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003173 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003174 sp<FakeWindowHandle> window =
3175 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003176 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003177
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003178 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003181 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003182 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003183 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003184 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003185}
3186
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003187TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3188 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003189
Chris Yea209fde2020-07-22 13:54:51 -07003190 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003191 sp<FakeWindowHandle> window =
3192 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003194
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003198 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003199 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003200
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003201 // Pilfer pointers from the monitor.
3202 // This should not do anything and the window should continue to receive events.
3203 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003206 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3207 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003208 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003209
3210 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3211 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003212}
3213
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003214TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003215 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3216 sp<FakeWindowHandle> window =
3217 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3219 window->setWindowOffset(20, 40);
3220 window->setWindowTransform(0, 1, -1, 0);
3221
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003222 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003223
3224 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3225 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3226 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3227 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3228 MotionEvent* event = monitor.consumeMotion();
3229 // Even though window has transform, gesture monitor must not.
3230 ASSERT_EQ(ui::Transform(), event->getTransform());
3231}
3232
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003233TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003234 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003235 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003236
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003237 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003238 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003239 << "Injection should fail if there is a monitor, but no touchable window";
3240 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003241}
3242
chaviw81e2bb92019-12-18 15:03:51 -08003243TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003244 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003245 sp<FakeWindowHandle> window =
3246 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3247
Arthur Hung72d8dc32020-03-28 00:48:39 +00003248 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003249
3250 NotifyMotionArgs motionArgs =
3251 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3252 ADISPLAY_ID_DEFAULT);
3253
3254 mDispatcher->notifyMotion(&motionArgs);
3255 // Window should receive motion down event.
3256 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3257
3258 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003259 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003260 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3261 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3262 motionArgs.pointerCoords[0].getX() - 10);
3263
3264 mDispatcher->notifyMotion(&motionArgs);
3265 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3266 0 /*expectedFlags*/);
3267}
3268
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003269/**
3270 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3271 * the device default right away. In the test scenario, we check both the default value,
3272 * and the action of enabling / disabling.
3273 */
3274TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003275 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003276 sp<FakeWindowHandle> window =
3277 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003278 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003279
3280 // Set focused application.
3281 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003282 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003283
3284 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003285 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003286 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003287 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3288
3289 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003290 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003292 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3293
3294 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003295 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3296 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003297 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003298 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003300 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003301 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3302
3303 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003304 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003306 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3307
3308 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003309 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3310 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003311 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003312 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003314 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003315 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3316
3317 window->assertNoEvents();
3318}
3319
Gang Wange9087892020-01-07 12:17:14 -05003320TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003321 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003322 sp<FakeWindowHandle> window =
3323 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3324
3325 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003326 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003327
Arthur Hung72d8dc32020-03-28 00:48:39 +00003328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003329 setFocusedWindow(window);
3330
Gang Wange9087892020-01-07 12:17:14 -05003331 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3332
3333 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3334 mDispatcher->notifyKey(&keyArgs);
3335
3336 InputEvent* event = window->consume();
3337 ASSERT_NE(event, nullptr);
3338
3339 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3340 ASSERT_NE(verified, nullptr);
3341 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3342
3343 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3344 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3345 ASSERT_EQ(keyArgs.source, verified->source);
3346 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3347
3348 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3349
3350 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003351 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003352 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003353 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3354 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3355 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3356 ASSERT_EQ(0, verifiedKey.repeatCount);
3357}
3358
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003359TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003360 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003361 sp<FakeWindowHandle> window =
3362 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3363
3364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3365
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003366 ui::Transform transform;
3367 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3368
3369 gui::DisplayInfo displayInfo;
3370 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3371 displayInfo.transform = transform;
3372
3373 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003374
3375 NotifyMotionArgs motionArgs =
3376 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3377 ADISPLAY_ID_DEFAULT);
3378 mDispatcher->notifyMotion(&motionArgs);
3379
3380 InputEvent* event = window->consume();
3381 ASSERT_NE(event, nullptr);
3382
3383 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3384 ASSERT_NE(verified, nullptr);
3385 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3386
3387 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3388 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3389 EXPECT_EQ(motionArgs.source, verified->source);
3390 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3391
3392 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3393
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003394 const vec2 rawXY =
3395 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3396 motionArgs.pointerCoords[0].getXYValue());
3397 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3398 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003399 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003400 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003401 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003402 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3403 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3404}
3405
chaviw09c8d2d2020-08-24 15:48:26 -07003406/**
3407 * Ensure that separate calls to sign the same data are generating the same key.
3408 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3409 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3410 * tests.
3411 */
3412TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3413 KeyEvent event = getTestKeyEvent();
3414 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3415
3416 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3417 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3418 ASSERT_EQ(hmac1, hmac2);
3419}
3420
3421/**
3422 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3423 */
3424TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3425 KeyEvent event = getTestKeyEvent();
3426 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3427 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3428
3429 verifiedEvent.deviceId += 1;
3430 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3431
3432 verifiedEvent.source += 1;
3433 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3434
3435 verifiedEvent.eventTimeNanos += 1;
3436 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3437
3438 verifiedEvent.displayId += 1;
3439 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3440
3441 verifiedEvent.action += 1;
3442 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3443
3444 verifiedEvent.downTimeNanos += 1;
3445 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3446
3447 verifiedEvent.flags += 1;
3448 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3449
3450 verifiedEvent.keyCode += 1;
3451 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3452
3453 verifiedEvent.scanCode += 1;
3454 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3455
3456 verifiedEvent.metaState += 1;
3457 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3458
3459 verifiedEvent.repeatCount += 1;
3460 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3461}
3462
Vishnu Nair958da932020-08-21 17:12:37 -07003463TEST_F(InputDispatcherTest, SetFocusedWindow) {
3464 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3465 sp<FakeWindowHandle> windowTop =
3466 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3467 sp<FakeWindowHandle> windowSecond =
3468 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3469 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3470
3471 // Top window is also focusable but is not granted focus.
3472 windowTop->setFocusable(true);
3473 windowSecond->setFocusable(true);
3474 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3475 setFocusedWindow(windowSecond);
3476
3477 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3479 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003480
3481 // Focused window should receive event.
3482 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3483 windowTop->assertNoEvents();
3484}
3485
3486TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3488 sp<FakeWindowHandle> window =
3489 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3490 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3491
3492 window->setFocusable(true);
3493 // Release channel for window is no longer valid.
3494 window->releaseChannel();
3495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3496 setFocusedWindow(window);
3497
3498 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003499 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3500 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003501
3502 // window channel is invalid, so it should not receive any input event.
3503 window->assertNoEvents();
3504}
3505
3506TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3507 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3508 sp<FakeWindowHandle> window =
3509 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003510 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003511 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3512
Vishnu Nair958da932020-08-21 17:12:37 -07003513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3514 setFocusedWindow(window);
3515
3516 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003517 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3518 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003519
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003520 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003521 window->assertNoEvents();
3522}
3523
3524TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3525 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3526 sp<FakeWindowHandle> windowTop =
3527 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3528 sp<FakeWindowHandle> windowSecond =
3529 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3530 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3531
3532 windowTop->setFocusable(true);
3533 windowSecond->setFocusable(true);
3534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3535 setFocusedWindow(windowTop);
3536 windowTop->consumeFocusEvent(true);
3537
3538 setFocusedWindow(windowSecond, windowTop);
3539 windowSecond->consumeFocusEvent(true);
3540 windowTop->consumeFocusEvent(false);
3541
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3543 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003544
3545 // Focused window should receive event.
3546 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3547}
3548
3549TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3550 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3551 sp<FakeWindowHandle> windowTop =
3552 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3553 sp<FakeWindowHandle> windowSecond =
3554 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3555 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3556
3557 windowTop->setFocusable(true);
3558 windowSecond->setFocusable(true);
3559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3560 setFocusedWindow(windowSecond, windowTop);
3561
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003562 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3563 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003564
3565 // Event should be dropped.
3566 windowTop->assertNoEvents();
3567 windowSecond->assertNoEvents();
3568}
3569
3570TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3572 sp<FakeWindowHandle> window =
3573 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3574 sp<FakeWindowHandle> previousFocusedWindow =
3575 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3576 ADISPLAY_ID_DEFAULT);
3577 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3578
3579 window->setFocusable(true);
3580 previousFocusedWindow->setFocusable(true);
3581 window->setVisible(false);
3582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3583 setFocusedWindow(previousFocusedWindow);
3584 previousFocusedWindow->consumeFocusEvent(true);
3585
3586 // Requesting focus on invisible window takes focus from currently focused window.
3587 setFocusedWindow(window);
3588 previousFocusedWindow->consumeFocusEvent(false);
3589
3590 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003592 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003593 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003594
3595 // Window does not get focus event or key down.
3596 window->assertNoEvents();
3597
3598 // Window becomes visible.
3599 window->setVisible(true);
3600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3601
3602 // Window receives focus event.
3603 window->consumeFocusEvent(true);
3604 // Focused window receives key down.
3605 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3606}
3607
Vishnu Nair599f1412021-06-21 10:39:58 -07003608TEST_F(InputDispatcherTest, DisplayRemoved) {
3609 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3610 sp<FakeWindowHandle> window =
3611 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3613
3614 // window is granted focus.
3615 window->setFocusable(true);
3616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3617 setFocusedWindow(window);
3618 window->consumeFocusEvent(true);
3619
3620 // When a display is removed window loses focus.
3621 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3622 window->consumeFocusEvent(false);
3623}
3624
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003625/**
3626 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3627 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3628 * of the 'slipperyEnterWindow'.
3629 *
3630 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3631 * a way so that the touched location is no longer covered by the top window.
3632 *
3633 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3634 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3635 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3636 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3637 * with ACTION_DOWN).
3638 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3639 * window moved itself away from the touched location and had Flag::SLIPPERY.
3640 *
3641 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3642 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3643 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3644 *
3645 * In this test, we ensure that the event received by the bottom window has
3646 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3647 */
3648TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003649 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3650 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003651
3652 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3653 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3654
3655 sp<FakeWindowHandle> slipperyExitWindow =
3656 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003657 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003658 // Make sure this one overlaps the bottom window
3659 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3660 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3661 // one. Windows with the same owner are not considered to be occluding each other.
3662 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3663
3664 sp<FakeWindowHandle> slipperyEnterWindow =
3665 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3666 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3667
3668 mDispatcher->setInputWindows(
3669 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3670
3671 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3672 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3673 ADISPLAY_ID_DEFAULT, {{50, 50}});
3674 mDispatcher->notifyMotion(&args);
3675 slipperyExitWindow->consumeMotionDown();
3676 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3677 mDispatcher->setInputWindows(
3678 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3679
3680 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3681 ADISPLAY_ID_DEFAULT, {{51, 51}});
3682 mDispatcher->notifyMotion(&args);
3683
3684 slipperyExitWindow->consumeMotionCancel();
3685
3686 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3687 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3688}
3689
Garfield Tan1c7bc862020-01-28 13:24:04 -08003690class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3691protected:
3692 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3693 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3694
Chris Yea209fde2020-07-22 13:54:51 -07003695 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003696 sp<FakeWindowHandle> mWindow;
3697
3698 virtual void SetUp() override {
3699 mFakePolicy = new FakeInputDispatcherPolicy();
3700 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003701 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003702 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3703 ASSERT_EQ(OK, mDispatcher->start());
3704
3705 setUpWindow();
3706 }
3707
3708 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003709 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003710 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3711
Vishnu Nair47074b82020-08-14 11:54:47 -07003712 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003714 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003715 mWindow->consumeFocusEvent(true);
3716 }
3717
Chris Ye2ad95392020-09-01 13:44:44 -07003718 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003719 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003720 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003721 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3722 mDispatcher->notifyKey(&keyArgs);
3723
3724 // Window should receive key down event.
3725 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3726 }
3727
3728 void expectKeyRepeatOnce(int32_t repeatCount) {
3729 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3730 InputEvent* repeatEvent = mWindow->consume();
3731 ASSERT_NE(nullptr, repeatEvent);
3732
3733 uint32_t eventType = repeatEvent->getType();
3734 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3735
3736 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3737 uint32_t eventAction = repeatKeyEvent->getAction();
3738 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3739 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3740 }
3741
Chris Ye2ad95392020-09-01 13:44:44 -07003742 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003743 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003744 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003745 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3746 mDispatcher->notifyKey(&keyArgs);
3747
3748 // Window should receive key down event.
3749 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3750 0 /*expectedFlags*/);
3751 }
3752};
3753
3754TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003755 sendAndConsumeKeyDown(1 /* deviceId */);
3756 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3757 expectKeyRepeatOnce(repeatCount);
3758 }
3759}
3760
3761TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3762 sendAndConsumeKeyDown(1 /* deviceId */);
3763 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3764 expectKeyRepeatOnce(repeatCount);
3765 }
3766 sendAndConsumeKeyDown(2 /* deviceId */);
3767 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003768 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3769 expectKeyRepeatOnce(repeatCount);
3770 }
3771}
3772
3773TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003774 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003775 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003776 sendAndConsumeKeyUp(1 /* deviceId */);
3777 mWindow->assertNoEvents();
3778}
3779
3780TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3781 sendAndConsumeKeyDown(1 /* deviceId */);
3782 expectKeyRepeatOnce(1 /*repeatCount*/);
3783 sendAndConsumeKeyDown(2 /* deviceId */);
3784 expectKeyRepeatOnce(1 /*repeatCount*/);
3785 // Stale key up from device 1.
3786 sendAndConsumeKeyUp(1 /* deviceId */);
3787 // Device 2 is still down, keep repeating
3788 expectKeyRepeatOnce(2 /*repeatCount*/);
3789 expectKeyRepeatOnce(3 /*repeatCount*/);
3790 // Device 2 key up
3791 sendAndConsumeKeyUp(2 /* deviceId */);
3792 mWindow->assertNoEvents();
3793}
3794
3795TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3796 sendAndConsumeKeyDown(1 /* deviceId */);
3797 expectKeyRepeatOnce(1 /*repeatCount*/);
3798 sendAndConsumeKeyDown(2 /* deviceId */);
3799 expectKeyRepeatOnce(1 /*repeatCount*/);
3800 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3801 sendAndConsumeKeyUp(2 /* deviceId */);
3802 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003803 mWindow->assertNoEvents();
3804}
3805
liushenxiang42232912021-05-21 20:24:09 +08003806TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3807 sendAndConsumeKeyDown(DEVICE_ID);
3808 expectKeyRepeatOnce(1 /*repeatCount*/);
3809 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3810 mDispatcher->notifyDeviceReset(&args);
3811 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3812 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3813 mWindow->assertNoEvents();
3814}
3815
Garfield Tan1c7bc862020-01-28 13:24:04 -08003816TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003817 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003818 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3819 InputEvent* repeatEvent = mWindow->consume();
3820 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3821 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3822 IdGenerator::getSource(repeatEvent->getId()));
3823 }
3824}
3825
3826TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003827 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003828
3829 std::unordered_set<int32_t> idSet;
3830 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3831 InputEvent* repeatEvent = mWindow->consume();
3832 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3833 int32_t id = repeatEvent->getId();
3834 EXPECT_EQ(idSet.end(), idSet.find(id));
3835 idSet.insert(id);
3836 }
3837}
3838
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003839/* Test InputDispatcher for MultiDisplay */
3840class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3841public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003842 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003843 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003844
Chris Yea209fde2020-07-22 13:54:51 -07003845 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003846 windowInPrimary =
3847 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003848
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003849 // Set focus window for primary display, but focused display would be second one.
3850 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003851 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003853 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003854 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003855
Chris Yea209fde2020-07-22 13:54:51 -07003856 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003857 windowInSecondary =
3858 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003859 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003860 // Set focus display to second one.
3861 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3862 // Set focus window for second display.
3863 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003864 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003865 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003866 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003867 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003868 }
3869
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003870 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003871 InputDispatcherTest::TearDown();
3872
Chris Yea209fde2020-07-22 13:54:51 -07003873 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003874 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003875 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003876 windowInSecondary.clear();
3877 }
3878
3879protected:
Chris Yea209fde2020-07-22 13:54:51 -07003880 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003881 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003882 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003883 sp<FakeWindowHandle> windowInSecondary;
3884};
3885
3886TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3887 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3889 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003891 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003892 windowInSecondary->assertNoEvents();
3893
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003894 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3897 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003898 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003899 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003900}
3901
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003902TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003903 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3905 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003906 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003907 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003908 windowInSecondary->assertNoEvents();
3909
3910 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003912 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003913 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003914 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003915
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003916 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003917 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003918
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003919 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003920 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3921 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003922
3923 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003924 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003925 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003926 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003927 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003928 windowInSecondary->assertNoEvents();
3929}
3930
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003931// Test per-display input monitors for motion event.
3932TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003933 FakeMonitorReceiver monitorInPrimary =
3934 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3935 FakeMonitorReceiver monitorInSecondary =
3936 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003937
3938 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3940 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3941 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003942 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003943 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003944 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003945 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003946
3947 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3949 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003951 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003952 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003953 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003954 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003955
3956 // Test inject a non-pointer motion event.
3957 // If specific a display, it will dispatch to the focused window of particular display,
3958 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003962 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003963 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003964 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003965 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003966}
3967
3968// Test per-display input monitors for key event.
3969TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003970 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003971 FakeMonitorReceiver monitorInPrimary =
3972 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3973 FakeMonitorReceiver monitorInSecondary =
3974 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003975
3976 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3978 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003979 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003980 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003981 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003982 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003983}
3984
Vishnu Nair958da932020-08-21 17:12:37 -07003985TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3986 sp<FakeWindowHandle> secondWindowInPrimary =
3987 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3988 secondWindowInPrimary->setFocusable(true);
3989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3990 setFocusedWindow(secondWindowInPrimary);
3991 windowInPrimary->consumeFocusEvent(false);
3992 secondWindowInPrimary->consumeFocusEvent(true);
3993
3994 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3996 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003997 windowInPrimary->assertNoEvents();
3998 windowInSecondary->assertNoEvents();
3999 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4000}
4001
Arthur Hungdfd528e2021-12-08 13:23:04 +00004002TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4003 FakeMonitorReceiver monitorInPrimary =
4004 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4005 FakeMonitorReceiver monitorInSecondary =
4006 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4007
4008 // Test touch down on primary display.
4009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4010 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4012 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4013 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4014
4015 // Test touch down on second display.
4016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4017 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4019 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4020 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4021
4022 // Trigger cancel touch.
4023 mDispatcher->cancelCurrentTouch();
4024 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4025 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4026 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4027 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4028
4029 // Test inject a move motion event, no window/monitor should receive the event.
4030 ASSERT_EQ(InputEventInjectionResult::FAILED,
4031 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4032 ADISPLAY_ID_DEFAULT, {110, 200}))
4033 << "Inject motion event should return InputEventInjectionResult::FAILED";
4034 windowInPrimary->assertNoEvents();
4035 monitorInPrimary.assertNoEvents();
4036
4037 ASSERT_EQ(InputEventInjectionResult::FAILED,
4038 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4039 SECOND_DISPLAY_ID, {110, 200}))
4040 << "Inject motion event should return InputEventInjectionResult::FAILED";
4041 windowInSecondary->assertNoEvents();
4042 monitorInSecondary.assertNoEvents();
4043}
4044
Jackal Guof9696682018-10-05 12:23:23 +08004045class InputFilterTest : public InputDispatcherTest {
4046protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004047 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4048 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004049 NotifyMotionArgs motionArgs;
4050
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004051 motionArgs =
4052 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004053 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004054 motionArgs =
4055 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004056 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004057 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004058 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004059 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4060 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004061 } else {
4062 mFakePolicy->assertFilterInputEventWasNotCalled();
4063 }
4064 }
4065
4066 void testNotifyKey(bool expectToBeFiltered) {
4067 NotifyKeyArgs keyArgs;
4068
4069 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4070 mDispatcher->notifyKey(&keyArgs);
4071 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4072 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004073 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004074
4075 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004076 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004077 } else {
4078 mFakePolicy->assertFilterInputEventWasNotCalled();
4079 }
4080 }
4081};
4082
4083// Test InputFilter for MotionEvent
4084TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4085 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4086 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4087 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4088
4089 // Enable InputFilter
4090 mDispatcher->setInputFilterEnabled(true);
4091 // Test touch on both primary and second display, and check if both events are filtered.
4092 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4093 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4094
4095 // Disable InputFilter
4096 mDispatcher->setInputFilterEnabled(false);
4097 // Test touch on both primary and second display, and check if both events aren't filtered.
4098 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4099 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4100}
4101
4102// Test InputFilter for KeyEvent
4103TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4104 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4105 testNotifyKey(/*expectToBeFiltered*/ false);
4106
4107 // Enable InputFilter
4108 mDispatcher->setInputFilterEnabled(true);
4109 // Send a key event, and check if it is filtered.
4110 testNotifyKey(/*expectToBeFiltered*/ true);
4111
4112 // Disable InputFilter
4113 mDispatcher->setInputFilterEnabled(false);
4114 // Send a key event, and check if it isn't filtered.
4115 testNotifyKey(/*expectToBeFiltered*/ false);
4116}
4117
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004118// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4119// logical display coordinate space.
4120TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4121 ui::Transform firstDisplayTransform;
4122 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4123 ui::Transform secondDisplayTransform;
4124 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4125
4126 std::vector<gui::DisplayInfo> displayInfos(2);
4127 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4128 displayInfos[0].transform = firstDisplayTransform;
4129 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4130 displayInfos[1].transform = secondDisplayTransform;
4131
4132 mDispatcher->onWindowInfosChanged({}, displayInfos);
4133
4134 // Enable InputFilter
4135 mDispatcher->setInputFilterEnabled(true);
4136
4137 // Ensure the correct transforms are used for the displays.
4138 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4139 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4140}
4141
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4143protected:
4144 virtual void SetUp() override {
4145 InputDispatcherTest::SetUp();
4146
4147 /**
4148 * We don't need to enable input filter to test the injected event policy, but we enabled it
4149 * here to make the tests more realistic, since this policy only matters when inputfilter is
4150 * on.
4151 */
4152 mDispatcher->setInputFilterEnabled(true);
4153
4154 std::shared_ptr<InputApplicationHandle> application =
4155 std::make_shared<FakeApplicationHandle>();
4156 mWindow =
4157 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4158
4159 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4160 mWindow->setFocusable(true);
4161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4162 setFocusedWindow(mWindow);
4163 mWindow->consumeFocusEvent(true);
4164 }
4165
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004166 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4167 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004168 KeyEvent event;
4169
4170 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4171 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4172 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4173 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4174 const int32_t additionalPolicyFlags =
4175 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004177 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4179 policyFlags | additionalPolicyFlags));
4180
4181 InputEvent* received = mWindow->consume();
4182 ASSERT_NE(nullptr, received);
4183 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004184 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4185 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4186 ASSERT_EQ(flags, keyEvent.getFlags());
4187 }
4188
4189 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4190 int32_t flags) {
4191 MotionEvent event;
4192 PointerProperties pointerProperties[1];
4193 PointerCoords pointerCoords[1];
4194 pointerProperties[0].clear();
4195 pointerProperties[0].id = 0;
4196 pointerCoords[0].clear();
4197 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4198 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4199
4200 ui::Transform identityTransform;
4201 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4202 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4203 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4204 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4205 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004206 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004207 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004208 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4209
4210 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004212 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004213 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4214 policyFlags | additionalPolicyFlags));
4215
4216 InputEvent* received = mWindow->consume();
4217 ASSERT_NE(nullptr, received);
4218 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4219 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4220 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4221 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004222 }
4223
4224private:
4225 sp<FakeWindowHandle> mWindow;
4226};
4227
4228TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004229 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4230 // filter. Without it, the event will no different from a regularly injected event, and the
4231 // injected device id will be overwritten.
4232 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4233 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234}
4235
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004236TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004238 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4239 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4240}
4241
4242TEST_F(InputFilterInjectionPolicyTest,
4243 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4244 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4245 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4246 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247}
4248
4249TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4250 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004251 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004252}
4253
chaviwfd6d3512019-03-25 13:23:49 -07004254class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004255 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004256 InputDispatcherTest::SetUp();
4257
Chris Yea209fde2020-07-22 13:54:51 -07004258 std::shared_ptr<FakeApplicationHandle> application =
4259 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004260 mUnfocusedWindow =
4261 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004262 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004263
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004264 mFocusedWindow =
4265 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4266 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004267
4268 // Set focused application.
4269 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004270 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004271
4272 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004274 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004275 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004276 }
4277
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004278 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004279 InputDispatcherTest::TearDown();
4280
4281 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004282 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004283 }
4284
4285protected:
4286 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004287 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004288 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004289};
4290
4291// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4292// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4293// the onPointerDownOutsideFocus callback.
4294TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004296 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4297 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004299 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004300
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004301 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004302 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4303}
4304
4305// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4306// DOWN on the window that doesn't have focus. Ensure no window received the
4307// onPointerDownOutsideFocus callback.
4308TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004310 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004312 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004313
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004314 ASSERT_TRUE(mDispatcher->waitForIdle());
4315 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004316}
4317
4318// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4319// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4320TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004321 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4322 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004324 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004325
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004326 ASSERT_TRUE(mDispatcher->waitForIdle());
4327 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004328}
4329
4330// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4331// DOWN on the window that already has focus. Ensure no window received the
4332// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004333TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004335 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004336 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004338 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004339
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004340 ASSERT_TRUE(mDispatcher->waitForIdle());
4341 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004342}
4343
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004344// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4345// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4346TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4347 const MotionEvent event =
4348 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4349 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4350 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4351 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4352 .build();
4353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4354 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4355 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4356
4357 ASSERT_TRUE(mDispatcher->waitForIdle());
4358 mFakePolicy->assertOnPointerDownWasNotCalled();
4359 // Ensure that the unfocused window did not receive any FOCUS events.
4360 mUnfocusedWindow->assertNoEvents();
4361}
4362
chaviwaf87b3e2019-10-01 16:59:28 -07004363// These tests ensures we can send touch events to a single client when there are multiple input
4364// windows that point to the same client token.
4365class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4366 virtual void SetUp() override {
4367 InputDispatcherTest::SetUp();
4368
Chris Yea209fde2020-07-22 13:54:51 -07004369 std::shared_ptr<FakeApplicationHandle> application =
4370 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004371 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4372 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004373 mWindow1->setFrame(Rect(0, 0, 100, 100));
4374
4375 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4376 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004377 mWindow2->setFrame(Rect(100, 100, 200, 200));
4378
Arthur Hung72d8dc32020-03-28 00:48:39 +00004379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004380 }
4381
4382protected:
4383 sp<FakeWindowHandle> mWindow1;
4384 sp<FakeWindowHandle> mWindow2;
4385
4386 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004387 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004388 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4389 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004390 }
4391
4392 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4393 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004394 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004395 InputEvent* event = window->consume();
4396
4397 ASSERT_NE(nullptr, event) << name.c_str()
4398 << ": consumer should have returned non-NULL event.";
4399
4400 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4401 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4402 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4403
4404 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004405 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004406
4407 for (size_t i = 0; i < points.size(); i++) {
4408 float expectedX = points[i].x;
4409 float expectedY = points[i].y;
4410
4411 EXPECT_EQ(expectedX, motionEvent.getX(i))
4412 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4413 << ", got " << motionEvent.getX(i);
4414 EXPECT_EQ(expectedY, motionEvent.getY(i))
4415 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4416 << ", got " << motionEvent.getY(i);
4417 }
4418 }
chaviw9eaa22c2020-07-01 16:21:27 -07004419
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004420 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004421 std::vector<PointF> expectedPoints) {
4422 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4423 ADISPLAY_ID_DEFAULT, touchedPoints);
4424 mDispatcher->notifyMotion(&motionArgs);
4425
4426 // Always consume from window1 since it's the window that has the InputReceiver
4427 consumeMotionEvent(mWindow1, action, expectedPoints);
4428 }
chaviwaf87b3e2019-10-01 16:59:28 -07004429};
4430
4431TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4432 // Touch Window 1
4433 PointF touchedPoint = {10, 10};
4434 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004435 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004436
4437 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004438 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004439
4440 // Touch Window 2
4441 touchedPoint = {150, 150};
4442 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004443 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004444}
4445
chaviw9eaa22c2020-07-01 16:21:27 -07004446TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4447 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004448 mWindow2->setWindowScale(0.5f, 0.5f);
4449
4450 // Touch Window 1
4451 PointF touchedPoint = {10, 10};
4452 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004453 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004454 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004455 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004456
4457 // Touch Window 2
4458 touchedPoint = {150, 150};
4459 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004460 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4461 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004462
chaviw9eaa22c2020-07-01 16:21:27 -07004463 // Update the transform so rotation is set
4464 mWindow2->setWindowTransform(0, -1, 1, 0);
4465 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4466 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004467}
4468
chaviw9eaa22c2020-07-01 16:21:27 -07004469TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004470 mWindow2->setWindowScale(0.5f, 0.5f);
4471
4472 // Touch Window 1
4473 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4474 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004475 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004476
4477 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004478 touchedPoints.push_back(PointF{150, 150});
4479 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004480 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004481
chaviw9eaa22c2020-07-01 16:21:27 -07004482 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004483 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004484 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004485
chaviw9eaa22c2020-07-01 16:21:27 -07004486 // Update the transform so rotation is set for Window 2
4487 mWindow2->setWindowTransform(0, -1, 1, 0);
4488 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004489 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004490}
4491
chaviw9eaa22c2020-07-01 16:21:27 -07004492TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004493 mWindow2->setWindowScale(0.5f, 0.5f);
4494
4495 // Touch Window 1
4496 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4497 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004498 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004499
4500 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004501 touchedPoints.push_back(PointF{150, 150});
4502 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004503
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004504 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004505
4506 // Move both windows
4507 touchedPoints = {{20, 20}, {175, 175}};
4508 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4509 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4510
chaviw9eaa22c2020-07-01 16:21:27 -07004511 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004512
chaviw9eaa22c2020-07-01 16:21:27 -07004513 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004514 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004515 expectedPoints.pop_back();
4516
4517 // Touch Window 2
4518 mWindow2->setWindowTransform(0, -1, 1, 0);
4519 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004520 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004521
4522 // Move both windows
4523 touchedPoints = {{20, 20}, {175, 175}};
4524 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4525 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4526
4527 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004528}
4529
4530TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4531 mWindow1->setWindowScale(0.5f, 0.5f);
4532
4533 // Touch Window 1
4534 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4535 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004536 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004537
4538 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004539 touchedPoints.push_back(PointF{150, 150});
4540 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004541
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004542 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004543
4544 // Move both windows
4545 touchedPoints = {{20, 20}, {175, 175}};
4546 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4547 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4548
chaviw9eaa22c2020-07-01 16:21:27 -07004549 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004550}
4551
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004552class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4553 virtual void SetUp() override {
4554 InputDispatcherTest::SetUp();
4555
Chris Yea209fde2020-07-22 13:54:51 -07004556 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004557 mApplication->setDispatchingTimeout(20ms);
4558 mWindow =
4559 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4560 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004561 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004562 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004563
4564 // Set focused application.
4565 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4566
4567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004568 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004569 mWindow->consumeFocusEvent(true);
4570 }
4571
4572 virtual void TearDown() override {
4573 InputDispatcherTest::TearDown();
4574 mWindow.clear();
4575 }
4576
4577protected:
Chris Yea209fde2020-07-22 13:54:51 -07004578 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004579 sp<FakeWindowHandle> mWindow;
4580 static constexpr PointF WINDOW_LOCATION = {20, 20};
4581
4582 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4585 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004587 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4588 WINDOW_LOCATION));
4589 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004590
4591 sp<FakeWindowHandle> addSpyWindow() {
4592 sp<FakeWindowHandle> spy =
4593 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4594 spy->setTrustedOverlay(true);
4595 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004596 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004597 spy->setDispatchingTimeout(30ms);
4598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4599 return spy;
4600 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004601};
4602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603// Send a tap and respond, which should not cause an ANR.
4604TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4605 tapOnWindow();
4606 mWindow->consumeMotionDown();
4607 mWindow->consumeMotionUp();
4608 ASSERT_TRUE(mDispatcher->waitForIdle());
4609 mFakePolicy->assertNotifyAnrWasNotCalled();
4610}
4611
4612// Send a regular key and respond, which should not cause an ANR.
4613TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004615 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4616 ASSERT_TRUE(mDispatcher->waitForIdle());
4617 mFakePolicy->assertNotifyAnrWasNotCalled();
4618}
4619
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004620TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4621 mWindow->setFocusable(false);
4622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4623 mWindow->consumeFocusEvent(false);
4624
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004625 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004626 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004627 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4628 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004630 // Key will not go to window because we have no focused window.
4631 // The 'no focused window' ANR timer should start instead.
4632
4633 // Now, the focused application goes away.
4634 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4635 // The key should get dropped and there should be no ANR.
4636
4637 ASSERT_TRUE(mDispatcher->waitForIdle());
4638 mFakePolicy->assertNotifyAnrWasNotCalled();
4639}
4640
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004641// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004642// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4643// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004644TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004645 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004646 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4647 WINDOW_LOCATION));
4648
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004649 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4650 ASSERT_TRUE(sequenceNum);
4651 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004652 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004654 mWindow->finishEvent(*sequenceNum);
4655 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4656 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004657 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004658 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004659}
4660
4661// Send a key to the app and have the app not respond right away.
4662TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4663 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004665 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4666 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004667 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004668 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004669 ASSERT_TRUE(mDispatcher->waitForIdle());
4670}
4671
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672// We have a focused application, but no focused window
4673TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004674 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4676 mWindow->consumeFocusEvent(false);
4677
4678 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004680 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4681 WINDOW_LOCATION));
4682 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4683 mDispatcher->waitForIdle();
4684 mFakePolicy->assertNotifyAnrWasNotCalled();
4685
4686 // Once a focused event arrives, we get an ANR for this application
4687 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4688 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004690 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004691 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004693 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004694 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 ASSERT_TRUE(mDispatcher->waitForIdle());
4696}
4697
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004698/**
4699 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4700 * there will not be an ANR.
4701 */
4702TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4703 mWindow->setFocusable(false);
4704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4705 mWindow->consumeFocusEvent(false);
4706
4707 KeyEvent event;
4708 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4709 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4710
4711 // Define a valid key down event that is stale (too old).
4712 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4713 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4714 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4715
4716 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4717
4718 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004719 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004720 InputEventInjectionSync::WAIT_FOR_RESULT,
4721 INJECT_EVENT_TIMEOUT, policyFlags);
4722 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4723 << "Injection should fail because the event is stale";
4724
4725 ASSERT_TRUE(mDispatcher->waitForIdle());
4726 mFakePolicy->assertNotifyAnrWasNotCalled();
4727 mWindow->assertNoEvents();
4728}
4729
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004731// Make sure that we don't notify policy twice about the same ANR.
4732TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004733 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4735 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736
4737 // Once a focused event arrives, we get an ANR for this application
4738 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4739 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004742 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004743 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004744 const std::chrono::duration appTimeout =
4745 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004746 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004748 std::this_thread::sleep_for(appTimeout);
4749 // ANR should not be raised again. It is up to policy to do that if it desires.
4750 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004751
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004752 // If we now get a focused window, the ANR should stop, but the policy handles that via
4753 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 ASSERT_TRUE(mDispatcher->waitForIdle());
4755}
4756
4757// We have a focused application, but no focused window
4758TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004759 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4761 mWindow->consumeFocusEvent(false);
4762
4763 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004764 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4767 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768
4769 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004770 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004771
4772 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004773 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 ASSERT_TRUE(mDispatcher->waitForIdle());
4775 mWindow->assertNoEvents();
4776}
4777
4778/**
4779 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4780 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4781 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4782 * the ANR mechanism should still work.
4783 *
4784 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4785 * DOWN event, while not responding on the second one.
4786 */
4787TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4788 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4789 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4790 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4791 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4792 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794
4795 // Now send ACTION_UP, with identical timestamp
4796 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4797 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4798 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4799 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801
4802 // We have now sent down and up. Let's consume first event and then ANR on the second.
4803 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4804 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004805 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806}
4807
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004808// A spy window can receive an ANR
4809TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4810 sp<FakeWindowHandle> spy = addSpyWindow();
4811
4812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4813 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4814 WINDOW_LOCATION));
4815 mWindow->consumeMotionDown();
4816
4817 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4818 ASSERT_TRUE(sequenceNum);
4819 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004820 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004821
4822 spy->finishEvent(*sequenceNum);
4823 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4824 0 /*flags*/);
4825 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004826 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004827}
4828
4829// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004831TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4832 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4835 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838
4839 // Stuck on the ACTION_UP
4840 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004841 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004843 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004845 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4846 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847
4848 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4849 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004850 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004851 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004852 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853}
4854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004857TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4858 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859
4860 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004861 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4862 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863
4864 mWindow->consumeMotionDown();
4865 // Stuck on the ACTION_UP
4866 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004867 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004869 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004870 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004871 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4872 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873
4874 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4875 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004876 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004878 spy->assertNoEvents();
4879}
4880
4881TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4882 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4883
4884 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4885
4886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4887 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4888 WINDOW_LOCATION));
4889
4890 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4891 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4892 ASSERT_TRUE(consumeSeq);
4893
Prabir Pradhanedd96402022-02-15 01:46:16 -08004894 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004895
4896 monitor.finishEvent(*consumeSeq);
4897 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4898
4899 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004900 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004901}
4902
4903// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4904// process events, you don't get an anr. When the window later becomes unresponsive again, you
4905// get an ANR again.
4906// 1. tap -> block on ACTION_UP -> receive ANR
4907// 2. consume all pending events (= queue becomes healthy again)
4908// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4909TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4910 tapOnWindow();
4911
4912 mWindow->consumeMotionDown();
4913 // Block on ACTION_UP
4914 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004915 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4917 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004918 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 mWindow->assertNoEvents();
4920
4921 tapOnWindow();
4922 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004923 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mWindow->consumeMotionUp();
4925
4926 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004927 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004928 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929 mWindow->assertNoEvents();
4930}
4931
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004932// If a connection remains unresponsive for a while, make sure policy is only notified once about
4933// it.
4934TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4937 WINDOW_LOCATION));
4938
4939 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004940 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004942 // 'notifyConnectionUnresponsive' should only be called once per connection
4943 mFakePolicy->assertNotifyAnrWasNotCalled();
4944 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945 mWindow->consumeMotionDown();
4946 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4947 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4948 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004949 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004950 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004951 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004952}
4953
4954/**
4955 * If a window is processing a motion event, and then a key event comes in, the key event should
4956 * not to to the focused window until the motion is processed.
4957 *
4958 * Warning!!!
4959 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4960 * and the injection timeout that we specify when injecting the key.
4961 * We must have the injection timeout (10ms) be smaller than
4962 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4963 *
4964 * If that value changes, this test should also change.
4965 */
4966TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4967 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4969
4970 tapOnWindow();
4971 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4972 ASSERT_TRUE(downSequenceNum);
4973 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4974 ASSERT_TRUE(upSequenceNum);
4975 // Don't finish the events yet, and send a key
4976 // Injection will "succeed" because we will eventually give up and send the key to the focused
4977 // window even if motions are still being processed. But because the injection timeout is short,
4978 // we will receive INJECTION_TIMED_OUT as the result.
4979
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004980 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004982 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4983 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984 // Key will not be sent to the window, yet, because the window is still processing events
4985 // and the key remains pending, waiting for the touch events to be processed
4986 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4987 ASSERT_FALSE(keySequenceNum);
4988
4989 std::this_thread::sleep_for(500ms);
4990 // if we wait long enough though, dispatcher will give up, and still send the key
4991 // to the focused window, even though we have not yet finished the motion event
4992 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4993 mWindow->finishEvent(*downSequenceNum);
4994 mWindow->finishEvent(*upSequenceNum);
4995}
4996
4997/**
4998 * If a window is processing a motion event, and then a key event comes in, the key event should
4999 * not go to the focused window until the motion is processed.
5000 * If then a new motion comes in, then the pending key event should be going to the currently
5001 * focused window right away.
5002 */
5003TEST_F(InputDispatcherSingleWindowAnr,
5004 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5005 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5007
5008 tapOnWindow();
5009 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5010 ASSERT_TRUE(downSequenceNum);
5011 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5012 ASSERT_TRUE(upSequenceNum);
5013 // Don't finish the events yet, and send a key
5014 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005016 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005017 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005018 // At this point, key is still pending, and should not be sent to the application yet.
5019 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5020 ASSERT_FALSE(keySequenceNum);
5021
5022 // Now tap down again. It should cause the pending key to go to the focused window right away.
5023 tapOnWindow();
5024 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5025 // the other events yet. We can finish events in any order.
5026 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5027 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5028 mWindow->consumeMotionDown();
5029 mWindow->consumeMotionUp();
5030 mWindow->assertNoEvents();
5031}
5032
5033class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5034 virtual void SetUp() override {
5035 InputDispatcherTest::SetUp();
5036
Chris Yea209fde2020-07-22 13:54:51 -07005037 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005038 mApplication->setDispatchingTimeout(10ms);
5039 mUnfocusedWindow =
5040 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5041 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005043 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005044
5045 mFocusedWindow =
5046 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005047 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005049
5050 // Set focused application.
5051 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005052 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005053
5054 // Expect one focus window exist in display.
5055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005056 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005057 mFocusedWindow->consumeFocusEvent(true);
5058 }
5059
5060 virtual void TearDown() override {
5061 InputDispatcherTest::TearDown();
5062
5063 mUnfocusedWindow.clear();
5064 mFocusedWindow.clear();
5065 }
5066
5067protected:
Chris Yea209fde2020-07-22 13:54:51 -07005068 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005069 sp<FakeWindowHandle> mUnfocusedWindow;
5070 sp<FakeWindowHandle> mFocusedWindow;
5071 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5072 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5073 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5074
5075 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5076
5077 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5078
5079private:
5080 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005081 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5083 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5086 location));
5087 }
5088};
5089
5090// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5091// should be ANR'd first.
5092TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5095 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005097 mFocusedWindow->consumeMotionDown();
5098 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5099 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5100 // We consumed all events, so no ANR
5101 ASSERT_TRUE(mDispatcher->waitForIdle());
5102 mFakePolicy->assertNotifyAnrWasNotCalled();
5103
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005105 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5106 FOCUSED_WINDOW_LOCATION));
5107 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5108 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005109
5110 const std::chrono::duration timeout =
5111 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005112 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005113 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5114 // sequence to make it consistent
5115 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005117 mFocusedWindow->consumeMotionDown();
5118 // This cancel is generated because the connection was unresponsive
5119 mFocusedWindow->consumeMotionCancel();
5120 mFocusedWindow->assertNoEvents();
5121 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005122 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005123 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5124 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005125 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005126}
5127
5128// If we have 2 windows with identical timeouts that are both unresponsive,
5129// it doesn't matter which order they should have ANR.
5130// But we should receive ANR for both.
5131TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5132 // Set the timeout for unfocused window to match the focused window
5133 mUnfocusedWindow->setDispatchingTimeout(10ms);
5134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5135
5136 tapOnFocusedWindow();
5137 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005138 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5139 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5140 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141
5142 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005143 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5144 mFocusedWindow->getToken() == anrConnectionToken2);
5145 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5146 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005147
5148 ASSERT_TRUE(mDispatcher->waitForIdle());
5149 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005150
5151 mFocusedWindow->consumeMotionDown();
5152 mFocusedWindow->consumeMotionUp();
5153 mUnfocusedWindow->consumeMotionOutside();
5154
Prabir Pradhanedd96402022-02-15 01:46:16 -08005155 sp<IBinder> responsiveToken1, responsiveToken2;
5156 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5157 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005158
5159 // Both applications should be marked as responsive, in any order
5160 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5161 mFocusedWindow->getToken() == responsiveToken2);
5162 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5163 mUnfocusedWindow->getToken() == responsiveToken2);
5164 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165}
5166
5167// If a window is already not responding, the second tap on the same window should be ignored.
5168// We should also log an error to account for the dropped event (not tested here).
5169// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5170TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5171 tapOnFocusedWindow();
5172 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5173 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5174 // Receive the events, but don't respond
5175 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5176 ASSERT_TRUE(downEventSequenceNum);
5177 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5178 ASSERT_TRUE(upEventSequenceNum);
5179 const std::chrono::duration timeout =
5180 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005181 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005182
5183 // Tap once again
5184 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005185 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005186 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5187 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005188 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005189 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5190 FOCUSED_WINDOW_LOCATION));
5191 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5192 // valid touch target
5193 mUnfocusedWindow->assertNoEvents();
5194
5195 // Consume the first tap
5196 mFocusedWindow->finishEvent(*downEventSequenceNum);
5197 mFocusedWindow->finishEvent(*upEventSequenceNum);
5198 ASSERT_TRUE(mDispatcher->waitForIdle());
5199 // The second tap did not go to the focused window
5200 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005201 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005202 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5203 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005204 mFakePolicy->assertNotifyAnrWasNotCalled();
5205}
5206
5207// If you tap outside of all windows, there will not be ANR
5208TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005209 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005210 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5211 LOCATION_OUTSIDE_ALL_WINDOWS));
5212 ASSERT_TRUE(mDispatcher->waitForIdle());
5213 mFakePolicy->assertNotifyAnrWasNotCalled();
5214}
5215
5216// Since the focused window is paused, tapping on it should not produce any events
5217TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5218 mFocusedWindow->setPaused(true);
5219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5220
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005221 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5223 FOCUSED_WINDOW_LOCATION));
5224
5225 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5226 ASSERT_TRUE(mDispatcher->waitForIdle());
5227 // Should not ANR because the window is paused, and touches shouldn't go to it
5228 mFakePolicy->assertNotifyAnrWasNotCalled();
5229
5230 mFocusedWindow->assertNoEvents();
5231 mUnfocusedWindow->assertNoEvents();
5232}
5233
5234/**
5235 * If a window is processing a motion event, and then a key event comes in, the key event should
5236 * not to to the focused window until the motion is processed.
5237 * If a different window becomes focused at this time, the key should go to that window instead.
5238 *
5239 * Warning!!!
5240 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5241 * and the injection timeout that we specify when injecting the key.
5242 * We must have the injection timeout (10ms) be smaller than
5243 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5244 *
5245 * If that value changes, this test should also change.
5246 */
5247TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5248 // Set a long ANR timeout to prevent it from triggering
5249 mFocusedWindow->setDispatchingTimeout(2s);
5250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5251
5252 tapOnUnfocusedWindow();
5253 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5254 ASSERT_TRUE(downSequenceNum);
5255 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5256 ASSERT_TRUE(upSequenceNum);
5257 // Don't finish the events yet, and send a key
5258 // Injection will succeed because we will eventually give up and send the key to the focused
5259 // window even if motions are still being processed.
5260
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005261 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005263 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005265 // Key will not be sent to the window, yet, because the window is still processing events
5266 // and the key remains pending, waiting for the touch events to be processed
5267 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5268 ASSERT_FALSE(keySequenceNum);
5269
5270 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005271 mFocusedWindow->setFocusable(false);
5272 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005274 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005275
5276 // Focus events should precede the key events
5277 mUnfocusedWindow->consumeFocusEvent(true);
5278 mFocusedWindow->consumeFocusEvent(false);
5279
5280 // Finish the tap events, which should unblock dispatcher
5281 mUnfocusedWindow->finishEvent(*downSequenceNum);
5282 mUnfocusedWindow->finishEvent(*upSequenceNum);
5283
5284 // Now that all queues are cleared and no backlog in the connections, the key event
5285 // can finally go to the newly focused "mUnfocusedWindow".
5286 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5287 mFocusedWindow->assertNoEvents();
5288 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005289 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005290}
5291
5292// When the touch stream is split across 2 windows, and one of them does not respond,
5293// then ANR should be raised and the touch should be canceled for the unresponsive window.
5294// The other window should not be affected by that.
5295TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5296 // Touch Window 1
5297 NotifyMotionArgs motionArgs =
5298 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5299 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5300 mDispatcher->notifyMotion(&motionArgs);
5301 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5302 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5303
5304 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005305 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5306 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005307 mDispatcher->notifyMotion(&motionArgs);
5308
5309 const std::chrono::duration timeout =
5310 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005311 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005312
5313 mUnfocusedWindow->consumeMotionDown();
5314 mFocusedWindow->consumeMotionDown();
5315 // Focused window may or may not receive ACTION_MOVE
5316 // But it should definitely receive ACTION_CANCEL due to the ANR
5317 InputEvent* event;
5318 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5319 ASSERT_TRUE(moveOrCancelSequenceNum);
5320 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5321 ASSERT_NE(nullptr, event);
5322 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5323 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5324 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5325 mFocusedWindow->consumeMotionCancel();
5326 } else {
5327 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5328 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005329 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005330 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5331 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005332
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005333 mUnfocusedWindow->assertNoEvents();
5334 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005335 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005336}
5337
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005338/**
5339 * If we have no focused window, and a key comes in, we start the ANR timer.
5340 * The focused application should add a focused window before the timer runs out to prevent ANR.
5341 *
5342 * If the user touches another application during this time, the key should be dropped.
5343 * Next, if a new focused window comes in, without toggling the focused application,
5344 * then no ANR should occur.
5345 *
5346 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5347 * but in some cases the policy may not update the focused application.
5348 */
5349TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5350 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5351 std::make_shared<FakeApplicationHandle>();
5352 focusedApplication->setDispatchingTimeout(60ms);
5353 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5354 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5355 mFocusedWindow->setFocusable(false);
5356
5357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5358 mFocusedWindow->consumeFocusEvent(false);
5359
5360 // Send a key. The ANR timer should start because there is no focused window.
5361 // 'focusedApplication' will get blamed if this timer completes.
5362 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005363 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005364 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005365 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5366 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005368
5369 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5370 // then the injected touches won't cause the focused event to get dropped.
5371 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5372 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5373 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5374 // For this test, it means that the key would get delivered to the window once it becomes
5375 // focused.
5376 std::this_thread::sleep_for(10ms);
5377
5378 // Touch unfocused window. This should force the pending key to get dropped.
5379 NotifyMotionArgs motionArgs =
5380 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5381 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5382 mDispatcher->notifyMotion(&motionArgs);
5383
5384 // We do not consume the motion right away, because that would require dispatcher to first
5385 // process (== drop) the key event, and by that time, ANR will be raised.
5386 // Set the focused window first.
5387 mFocusedWindow->setFocusable(true);
5388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5389 setFocusedWindow(mFocusedWindow);
5390 mFocusedWindow->consumeFocusEvent(true);
5391 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5392 // to another application. This could be a bug / behaviour in the policy.
5393
5394 mUnfocusedWindow->consumeMotionDown();
5395
5396 ASSERT_TRUE(mDispatcher->waitForIdle());
5397 // Should not ANR because we actually have a focused window. It was just added too slowly.
5398 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5399}
5400
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005401// These tests ensure we cannot send touch events to a window that's positioned behind a window
5402// that has feature NO_INPUT_CHANNEL.
5403// Layout:
5404// Top (closest to user)
5405// mNoInputWindow (above all windows)
5406// mBottomWindow
5407// Bottom (furthest from user)
5408class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5409 virtual void SetUp() override {
5410 InputDispatcherTest::SetUp();
5411
5412 mApplication = std::make_shared<FakeApplicationHandle>();
5413 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5414 "Window without input channel", ADISPLAY_ID_DEFAULT,
5415 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5416
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005417 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005418 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5419 // It's perfectly valid for this window to not have an associated input channel
5420
5421 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5422 ADISPLAY_ID_DEFAULT);
5423 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5424
5425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5426 }
5427
5428protected:
5429 std::shared_ptr<FakeApplicationHandle> mApplication;
5430 sp<FakeWindowHandle> mNoInputWindow;
5431 sp<FakeWindowHandle> mBottomWindow;
5432};
5433
5434TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5435 PointF touchedPoint = {10, 10};
5436
5437 NotifyMotionArgs motionArgs =
5438 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5439 ADISPLAY_ID_DEFAULT, {touchedPoint});
5440 mDispatcher->notifyMotion(&motionArgs);
5441
5442 mNoInputWindow->assertNoEvents();
5443 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5444 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5445 // and therefore should prevent mBottomWindow from receiving touches
5446 mBottomWindow->assertNoEvents();
5447}
5448
5449/**
5450 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5451 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5452 */
5453TEST_F(InputDispatcherMultiWindowOcclusionTests,
5454 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5455 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5456 "Window with input channel and NO_INPUT_CHANNEL",
5457 ADISPLAY_ID_DEFAULT);
5458
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005459 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005460 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5462
5463 PointF touchedPoint = {10, 10};
5464
5465 NotifyMotionArgs motionArgs =
5466 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5467 ADISPLAY_ID_DEFAULT, {touchedPoint});
5468 mDispatcher->notifyMotion(&motionArgs);
5469
5470 mNoInputWindow->assertNoEvents();
5471 mBottomWindow->assertNoEvents();
5472}
5473
Vishnu Nair958da932020-08-21 17:12:37 -07005474class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5475protected:
5476 std::shared_ptr<FakeApplicationHandle> mApp;
5477 sp<FakeWindowHandle> mWindow;
5478 sp<FakeWindowHandle> mMirror;
5479
5480 virtual void SetUp() override {
5481 InputDispatcherTest::SetUp();
5482 mApp = std::make_shared<FakeApplicationHandle>();
5483 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5484 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5485 mWindow->getToken());
5486 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5487 mWindow->setFocusable(true);
5488 mMirror->setFocusable(true);
5489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5490 }
5491};
5492
5493TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5494 // Request focus on a mirrored window
5495 setFocusedWindow(mMirror);
5496
5497 // window gets focused
5498 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5500 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005501 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5502}
5503
5504// A focused & mirrored window remains focused only if the window and its mirror are both
5505// focusable.
5506TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5507 setFocusedWindow(mMirror);
5508
5509 // window gets focused
5510 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5512 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005513 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5515 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005516 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5517
5518 mMirror->setFocusable(false);
5519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5520
5521 // window loses focus since one of the windows associated with the token in not focusable
5522 mWindow->consumeFocusEvent(false);
5523
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005524 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5525 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005526 mWindow->assertNoEvents();
5527}
5528
5529// A focused & mirrored window remains focused until the window and its mirror both become
5530// invisible.
5531TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5532 setFocusedWindow(mMirror);
5533
5534 // window gets focused
5535 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5537 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005538 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5540 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005541 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5542
5543 mMirror->setVisible(false);
5544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5545
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5547 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005548 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5550 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005551 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5552
5553 mWindow->setVisible(false);
5554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5555
5556 // window loses focus only after all windows associated with the token become invisible.
5557 mWindow->consumeFocusEvent(false);
5558
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005559 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5560 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005561 mWindow->assertNoEvents();
5562}
5563
5564// A focused & mirrored window remains focused until both windows are removed.
5565TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5566 setFocusedWindow(mMirror);
5567
5568 // window gets focused
5569 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5571 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005572 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5574 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005575 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5576
5577 // single window is removed but the window token remains focused
5578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5579
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5581 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005582 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5584 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005585 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5586
5587 // Both windows are removed
5588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5589 mWindow->consumeFocusEvent(false);
5590
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005591 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5592 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005593 mWindow->assertNoEvents();
5594}
5595
5596// Focus request can be pending until one window becomes visible.
5597TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5598 // Request focus on an invisible mirror.
5599 mWindow->setVisible(false);
5600 mMirror->setVisible(false);
5601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5602 setFocusedWindow(mMirror);
5603
5604 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005606 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005608
5609 mMirror->setVisible(true);
5610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5611
5612 // window gets focused
5613 mWindow->consumeFocusEvent(true);
5614 // window gets the pending key event
5615 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5616}
Prabir Pradhan99987712020-11-10 18:43:05 -08005617
5618class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5619protected:
5620 std::shared_ptr<FakeApplicationHandle> mApp;
5621 sp<FakeWindowHandle> mWindow;
5622 sp<FakeWindowHandle> mSecondWindow;
5623
5624 void SetUp() override {
5625 InputDispatcherTest::SetUp();
5626 mApp = std::make_shared<FakeApplicationHandle>();
5627 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5628 mWindow->setFocusable(true);
5629 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5630 mSecondWindow->setFocusable(true);
5631
5632 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5633 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5634
5635 setFocusedWindow(mWindow);
5636 mWindow->consumeFocusEvent(true);
5637 }
5638
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005639 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5640 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005641 mDispatcher->notifyPointerCaptureChanged(&args);
5642 }
5643
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005644 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5645 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005646 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005647 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5648 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005649 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005650 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005651 }
5652};
5653
5654TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5655 // Ensure that capture cannot be obtained for unfocused windows.
5656 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5657 mFakePolicy->assertSetPointerCaptureNotCalled();
5658 mSecondWindow->assertNoEvents();
5659
5660 // Ensure that capture can be enabled from the focus window.
5661 requestAndVerifyPointerCapture(mWindow, true);
5662
5663 // Ensure that capture cannot be disabled from a window that does not have capture.
5664 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5665 mFakePolicy->assertSetPointerCaptureNotCalled();
5666
5667 // Ensure that capture can be disabled from the window with capture.
5668 requestAndVerifyPointerCapture(mWindow, false);
5669}
5670
5671TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005672 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005673
5674 setFocusedWindow(mSecondWindow);
5675
5676 // Ensure that the capture disabled event was sent first.
5677 mWindow->consumeCaptureEvent(false);
5678 mWindow->consumeFocusEvent(false);
5679 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005680 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005681
5682 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005683 notifyPointerCaptureChanged({});
5684 notifyPointerCaptureChanged(request);
5685 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005686 mWindow->assertNoEvents();
5687 mSecondWindow->assertNoEvents();
5688 mFakePolicy->assertSetPointerCaptureNotCalled();
5689}
5690
5691TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005692 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005693
5694 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005695 notifyPointerCaptureChanged({});
5696 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005697
5698 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005699 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005700 mWindow->consumeCaptureEvent(false);
5701 mWindow->assertNoEvents();
5702}
5703
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005704TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5705 requestAndVerifyPointerCapture(mWindow, true);
5706
5707 // The first window loses focus.
5708 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005709 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005710 mWindow->consumeCaptureEvent(false);
5711
5712 // Request Pointer Capture from the second window before the notification from InputReader
5713 // arrives.
5714 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005715 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005716
5717 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005718 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005719
5720 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005721 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005722
5723 mSecondWindow->consumeFocusEvent(true);
5724 mSecondWindow->consumeCaptureEvent(true);
5725}
5726
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005727TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5728 // App repeatedly enables and disables capture.
5729 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5730 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5731 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5732 mFakePolicy->assertSetPointerCaptureCalled(false);
5733 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5734 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5735
5736 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5737 // first request is now stale, this should do nothing.
5738 notifyPointerCaptureChanged(firstRequest);
5739 mWindow->assertNoEvents();
5740
5741 // InputReader notifies that the second request was enabled.
5742 notifyPointerCaptureChanged(secondRequest);
5743 mWindow->consumeCaptureEvent(true);
5744}
5745
Prabir Pradhan7092e262022-05-03 16:51:09 +00005746TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5747 requestAndVerifyPointerCapture(mWindow, true);
5748
5749 // App toggles pointer capture off and on.
5750 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5751 mFakePolicy->assertSetPointerCaptureCalled(false);
5752
5753 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5754 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5755
5756 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5757 // preceding "disable" request.
5758 notifyPointerCaptureChanged(enableRequest);
5759
5760 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5761 // any notifications.
5762 mWindow->assertNoEvents();
5763}
5764
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005765class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5766protected:
5767 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005768
5769 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5770 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5771
5772 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5773 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5774
5775 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5776 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5777 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5778 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5779 MAXIMUM_OBSCURING_OPACITY);
5780
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005781 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005782 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005783 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005784
5785 sp<FakeWindowHandle> mTouchWindow;
5786
5787 virtual void SetUp() override {
5788 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005789 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005790 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5791 }
5792
5793 virtual void TearDown() override {
5794 InputDispatcherTest::TearDown();
5795 mTouchWindow.clear();
5796 }
5797
chaviw3277faf2021-05-19 16:45:23 -05005798 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5799 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005800 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005801 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005802 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005803 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005804 return window;
5805 }
5806
5807 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5808 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5809 sp<FakeWindowHandle> window =
5810 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5811 // Generate an arbitrary PID based on the UID
5812 window->setOwnerInfo(1777 + (uid % 10000), uid);
5813 return window;
5814 }
5815
5816 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5817 NotifyMotionArgs args =
5818 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5819 ADISPLAY_ID_DEFAULT, points);
5820 mDispatcher->notifyMotion(&args);
5821 }
5822};
5823
5824TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005825 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005826 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005828
5829 touch();
5830
5831 mTouchWindow->assertNoEvents();
5832}
5833
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005834TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005835 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5836 const sp<FakeWindowHandle>& w =
5837 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5839
5840 touch();
5841
5842 mTouchWindow->assertNoEvents();
5843}
5844
5845TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005846 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5847 const sp<FakeWindowHandle>& w =
5848 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5850
5851 touch();
5852
5853 w->assertNoEvents();
5854}
5855
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005856TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005857 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005859
5860 touch();
5861
5862 mTouchWindow->consumeAnyMotionDown();
5863}
5864
5865TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005866 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005867 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005868 w->setFrame(Rect(0, 0, 50, 50));
5869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005870
5871 touch({PointF{100, 100}});
5872
5873 mTouchWindow->consumeAnyMotionDown();
5874}
5875
5876TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005877 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005878 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5880
5881 touch();
5882
5883 mTouchWindow->consumeAnyMotionDown();
5884}
5885
5886TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5887 const sp<FakeWindowHandle>& w =
5888 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005890
5891 touch();
5892
5893 mTouchWindow->consumeAnyMotionDown();
5894}
5895
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005896TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5897 const sp<FakeWindowHandle>& w =
5898 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5900
5901 touch();
5902
5903 w->assertNoEvents();
5904}
5905
5906/**
5907 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5908 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5909 * window, the occluding window will still receive ACTION_OUTSIDE event.
5910 */
5911TEST_F(InputDispatcherUntrustedTouchesTest,
5912 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5913 const sp<FakeWindowHandle>& w =
5914 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005915 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5917
5918 touch();
5919
5920 w->consumeMotionOutside();
5921}
5922
5923TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5924 const sp<FakeWindowHandle>& w =
5925 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005926 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5928
5929 touch();
5930
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005931 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005932}
5933
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005934TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005935 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005936 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5937 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5939
5940 touch();
5941
5942 mTouchWindow->consumeAnyMotionDown();
5943}
5944
5945TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5946 const sp<FakeWindowHandle>& w =
5947 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5948 MAXIMUM_OBSCURING_OPACITY);
5949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005950
5951 touch();
5952
5953 mTouchWindow->consumeAnyMotionDown();
5954}
5955
5956TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005957 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005958 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5959 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5961
5962 touch();
5963
5964 mTouchWindow->assertNoEvents();
5965}
5966
5967TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5968 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5969 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005970 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5971 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005972 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005973 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5974 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5976
5977 touch();
5978
5979 mTouchWindow->assertNoEvents();
5980}
5981
5982TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5983 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5984 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005985 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5986 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005987 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005988 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5989 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005990 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5991
5992 touch();
5993
5994 mTouchWindow->consumeAnyMotionDown();
5995}
5996
5997TEST_F(InputDispatcherUntrustedTouchesTest,
5998 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5999 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006000 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6001 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006002 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006003 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6004 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6006
6007 touch();
6008
6009 mTouchWindow->consumeAnyMotionDown();
6010}
6011
6012TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6013 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006014 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6015 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006016 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006017 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6018 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006020
6021 touch();
6022
6023 mTouchWindow->assertNoEvents();
6024}
6025
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006026TEST_F(InputDispatcherUntrustedTouchesTest,
6027 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6028 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006029 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6030 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006031 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006032 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6033 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006034 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6035
6036 touch();
6037
6038 mTouchWindow->assertNoEvents();
6039}
6040
6041TEST_F(InputDispatcherUntrustedTouchesTest,
6042 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6043 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006044 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6045 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006046 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006047 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6048 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6050
6051 touch();
6052
6053 mTouchWindow->consumeAnyMotionDown();
6054}
6055
6056TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6057 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006058 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6059 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6061
6062 touch();
6063
6064 mTouchWindow->consumeAnyMotionDown();
6065}
6066
6067TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6068 const sp<FakeWindowHandle>& w =
6069 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6071
6072 touch();
6073
6074 mTouchWindow->consumeAnyMotionDown();
6075}
6076
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006077TEST_F(InputDispatcherUntrustedTouchesTest,
6078 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6079 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6080 const sp<FakeWindowHandle>& w =
6081 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6083
6084 touch();
6085
6086 mTouchWindow->assertNoEvents();
6087}
6088
6089TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6090 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6091 const sp<FakeWindowHandle>& w =
6092 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6094
6095 touch();
6096
6097 mTouchWindow->consumeAnyMotionDown();
6098}
6099
6100TEST_F(InputDispatcherUntrustedTouchesTest,
6101 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6102 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6103 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006104 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6105 OPACITY_ABOVE_THRESHOLD);
6106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6107
6108 touch();
6109
6110 mTouchWindow->consumeAnyMotionDown();
6111}
6112
6113TEST_F(InputDispatcherUntrustedTouchesTest,
6114 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6115 const sp<FakeWindowHandle>& w1 =
6116 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6117 OPACITY_BELOW_THRESHOLD);
6118 const sp<FakeWindowHandle>& w2 =
6119 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6120 OPACITY_BELOW_THRESHOLD);
6121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6122
6123 touch();
6124
6125 mTouchWindow->assertNoEvents();
6126}
6127
6128/**
6129 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6130 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6131 * (which alone would result in allowing touches) does not affect the blocking behavior.
6132 */
6133TEST_F(InputDispatcherUntrustedTouchesTest,
6134 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6135 const sp<FakeWindowHandle>& wB =
6136 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6137 OPACITY_BELOW_THRESHOLD);
6138 const sp<FakeWindowHandle>& wC =
6139 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6140 OPACITY_BELOW_THRESHOLD);
6141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6142
6143 touch();
6144
6145 mTouchWindow->assertNoEvents();
6146}
6147
6148/**
6149 * This test is testing that a window from a different UID but with same application token doesn't
6150 * block the touch. Apps can share the application token for close UI collaboration for example.
6151 */
6152TEST_F(InputDispatcherUntrustedTouchesTest,
6153 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6154 const sp<FakeWindowHandle>& w =
6155 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6156 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6158
6159 touch();
6160
6161 mTouchWindow->consumeAnyMotionDown();
6162}
6163
arthurhungb89ccb02020-12-30 16:19:01 +08006164class InputDispatcherDragTests : public InputDispatcherTest {
6165protected:
6166 std::shared_ptr<FakeApplicationHandle> mApp;
6167 sp<FakeWindowHandle> mWindow;
6168 sp<FakeWindowHandle> mSecondWindow;
6169 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006170 sp<FakeWindowHandle> mSpyWindow;
arthurhungb89ccb02020-12-30 16:19:01 +08006171
6172 void SetUp() override {
6173 InputDispatcherTest::SetUp();
6174 mApp = std::make_shared<FakeApplicationHandle>();
6175 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6176 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006177
6178 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6179 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006180
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006181 mSpyWindow = new FakeWindowHandle(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
6182 mSpyWindow->setSpy(true);
6183 mSpyWindow->setTrustedOverlay(true);
6184 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6185
arthurhungb89ccb02020-12-30 16:19:01 +08006186 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006187 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006188 }
6189
Arthur Hung54745652022-04-20 07:17:41 +00006190 void injectDown() {
arthurhungb89ccb02020-12-30 16:19:01 +08006191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6192 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6193 {50, 50}))
6194 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6195
6196 // Window should receive motion event.
6197 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006198 // Spy window should also receive motion event
6199 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006200 }
6201
6202 // Start performing drag, we will create a drag window and transfer touch to it.
6203 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6204 // Returns true on success.
6205 bool performDrag(bool sendDown = true) {
6206 if (sendDown) {
6207 injectDown();
6208 }
arthurhungb89ccb02020-12-30 16:19:01 +08006209
6210 // The drag window covers the entire display
6211 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006212 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006213 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006214 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006215
6216 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006217 bool transferred =
6218 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6219 true /* isDragDrop */);
6220 if (transferred) {
6221 mWindow->consumeMotionCancel();
6222 mDragWindow->consumeMotionDown();
6223 }
6224 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006225 }
arthurhung6d4bed92021-03-17 11:59:33 +08006226
6227 // Start performing drag, we will create a drag window and transfer touch to it.
6228 void performStylusDrag() {
6229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6230 injectMotionEvent(mDispatcher,
6231 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6232 AINPUT_SOURCE_STYLUS)
6233 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6234 .pointer(PointerBuilder(0,
6235 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6236 .x(50)
6237 .y(50))
6238 .build()));
6239 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6240
6241 // The drag window covers the entire display
6242 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6243 mDispatcher->setInputWindows(
6244 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6245
6246 // Transfer touch focus to the drag window
6247 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6248 true /* isDragDrop */);
6249 mWindow->consumeMotionCancel();
6250 mDragWindow->consumeMotionDown();
6251 }
arthurhungb89ccb02020-12-30 16:19:01 +08006252};
6253
6254TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6255 performDrag();
6256
6257 // Move on window.
6258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6259 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6260 ADISPLAY_ID_DEFAULT, {50, 50}))
6261 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6262 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6263 mWindow->consumeDragEvent(false, 50, 50);
6264 mSecondWindow->assertNoEvents();
6265
6266 // Move to another window.
6267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6268 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6269 ADISPLAY_ID_DEFAULT, {150, 50}))
6270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6271 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6272 mWindow->consumeDragEvent(true, 150, 50);
6273 mSecondWindow->consumeDragEvent(false, 50, 50);
6274
6275 // Move back to original window.
6276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6277 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6278 ADISPLAY_ID_DEFAULT, {50, 50}))
6279 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6280 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6281 mWindow->consumeDragEvent(false, 50, 50);
6282 mSecondWindow->consumeDragEvent(true, -50, 50);
6283
6284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6285 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6286 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6287 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6288 mWindow->assertNoEvents();
6289 mSecondWindow->assertNoEvents();
6290}
6291
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006292TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
6293 performDrag();
6294
6295 // No cancel event after drag start
6296 mSpyWindow->assertNoEvents();
6297
6298 const MotionEvent secondFingerDownEvent =
6299 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6300 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6301 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6302 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6303 .build();
6304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6305 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6306 InputEventInjectionSync::WAIT_FOR_RESULT))
6307 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6308
6309 // Receives cancel for first pointer after next pointer down
6310 mSpyWindow->consumeMotionCancel();
6311 mSpyWindow->consumeMotionDown();
6312
6313 mSpyWindow->assertNoEvents();
6314}
6315
arthurhungf452d0b2021-01-06 00:19:52 +08006316TEST_F(InputDispatcherDragTests, DragAndDrop) {
6317 performDrag();
6318
6319 // Move on window.
6320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6321 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6322 ADISPLAY_ID_DEFAULT, {50, 50}))
6323 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6324 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6325 mWindow->consumeDragEvent(false, 50, 50);
6326 mSecondWindow->assertNoEvents();
6327
6328 // Move to another window.
6329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6330 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6331 ADISPLAY_ID_DEFAULT, {150, 50}))
6332 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6333 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6334 mWindow->consumeDragEvent(true, 150, 50);
6335 mSecondWindow->consumeDragEvent(false, 50, 50);
6336
6337 // drop to another window.
6338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6339 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6340 {150, 50}))
6341 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6342 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6343 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6344 mWindow->assertNoEvents();
6345 mSecondWindow->assertNoEvents();
6346}
6347
arthurhung6d4bed92021-03-17 11:59:33 +08006348TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6349 performStylusDrag();
6350
6351 // Move on window and keep button pressed.
6352 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6353 injectMotionEvent(mDispatcher,
6354 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6355 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6356 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6357 .x(50)
6358 .y(50))
6359 .build()))
6360 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6361 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6362 mWindow->consumeDragEvent(false, 50, 50);
6363 mSecondWindow->assertNoEvents();
6364
6365 // Move to another window and release button, expect to drop item.
6366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6367 injectMotionEvent(mDispatcher,
6368 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6369 .buttonState(0)
6370 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6371 .x(150)
6372 .y(50))
6373 .build()))
6374 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6375 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6376 mWindow->assertNoEvents();
6377 mSecondWindow->assertNoEvents();
6378 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6379
6380 // nothing to the window.
6381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6382 injectMotionEvent(mDispatcher,
6383 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6384 .buttonState(0)
6385 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6386 .x(150)
6387 .y(50))
6388 .build()))
6389 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6390 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6391 mWindow->assertNoEvents();
6392 mSecondWindow->assertNoEvents();
6393}
6394
Arthur Hung54745652022-04-20 07:17:41 +00006395TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08006396 performDrag();
6397
6398 // Set second window invisible.
6399 mSecondWindow->setVisible(false);
6400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6401
6402 // Move on window.
6403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6404 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6405 ADISPLAY_ID_DEFAULT, {50, 50}))
6406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6407 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6408 mWindow->consumeDragEvent(false, 50, 50);
6409 mSecondWindow->assertNoEvents();
6410
6411 // Move to another window.
6412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6413 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6414 ADISPLAY_ID_DEFAULT, {150, 50}))
6415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6416 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6417 mWindow->consumeDragEvent(true, 150, 50);
6418 mSecondWindow->assertNoEvents();
6419
6420 // drop to another window.
6421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6422 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6423 {150, 50}))
6424 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6425 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6426 mFakePolicy->assertDropTargetEquals(nullptr);
6427 mWindow->assertNoEvents();
6428 mSecondWindow->assertNoEvents();
6429}
6430
Arthur Hung54745652022-04-20 07:17:41 +00006431TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6434 {50, 50}))
6435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6436 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6437
6438 const MotionEvent secondFingerDownEvent =
6439 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6440 .displayId(ADISPLAY_ID_DEFAULT)
6441 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6442 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6443 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6444 .build();
6445 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6446 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6447 InputEventInjectionSync::WAIT_FOR_RESULT))
6448 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6449 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6450
6451 // Should not perform drag and drop when window has multi fingers.
6452 ASSERT_FALSE(performDrag(false));
6453}
6454
6455TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6456 // First down on second window.
6457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6459 {150, 50}))
6460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6461
6462 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6463
6464 // Second down on first window.
6465 const MotionEvent secondFingerDownEvent =
6466 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6467 .displayId(ADISPLAY_ID_DEFAULT)
6468 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6469 .pointer(
6470 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6471 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6472 .build();
6473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6474 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6475 InputEventInjectionSync::WAIT_FOR_RESULT))
6476 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6477 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6478
6479 // Perform drag and drop from first window.
6480 ASSERT_TRUE(performDrag(false));
6481
6482 // Move on window.
6483 const MotionEvent secondFingerMoveEvent =
6484 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6485 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6486 .pointer(
6487 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6488 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6489 .build();
6490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6491 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6492 InputEventInjectionSync::WAIT_FOR_RESULT));
6493 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6494 mWindow->consumeDragEvent(false, 50, 50);
6495 mSecondWindow->consumeMotionMove();
6496
6497 // Release the drag pointer should perform drop.
6498 const MotionEvent secondFingerUpEvent =
6499 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6500 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6501 .pointer(
6502 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6503 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6504 .build();
6505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6506 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6507 InputEventInjectionSync::WAIT_FOR_RESULT));
6508 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6509 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6510 mWindow->assertNoEvents();
6511 mSecondWindow->consumeMotionMove();
6512}
6513
Arthur Hung3915c1f2022-05-31 07:17:17 +00006514TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
6515 performDrag();
6516
6517 // Update window of second display.
6518 sp<FakeWindowHandle> windowInSecondary =
6519 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6520 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6521
6522 // Let second display has a touch state.
6523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6524 injectMotionEvent(mDispatcher,
6525 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6526 AINPUT_SOURCE_TOUCHSCREEN)
6527 .displayId(SECOND_DISPLAY_ID)
6528 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6529 .x(100)
6530 .y(100))
6531 .build()));
6532 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6533 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6534 // Update window again.
6535 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6536
6537 // Move on window.
6538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6539 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6540 ADISPLAY_ID_DEFAULT, {50, 50}))
6541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6542 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6543 mWindow->consumeDragEvent(false, 50, 50);
6544 mSecondWindow->assertNoEvents();
6545
6546 // Move to another window.
6547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6548 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6549 ADISPLAY_ID_DEFAULT, {150, 50}))
6550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6551 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6552 mWindow->consumeDragEvent(true, 150, 50);
6553 mSecondWindow->consumeDragEvent(false, 50, 50);
6554
6555 // drop to another window.
6556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6557 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6558 {150, 50}))
6559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6560 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6561 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6562 mWindow->assertNoEvents();
6563 mSecondWindow->assertNoEvents();
6564}
6565
Vishnu Nair062a8672021-09-03 16:07:44 -07006566class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6567
6568TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6570 sp<FakeWindowHandle> window =
6571 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006572 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006573 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6574 window->setFocusable(true);
6575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6576 setFocusedWindow(window);
6577 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6578
6579 // With the flag set, window should not get any input
6580 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6581 mDispatcher->notifyKey(&keyArgs);
6582 window->assertNoEvents();
6583
6584 NotifyMotionArgs motionArgs =
6585 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6586 ADISPLAY_ID_DEFAULT);
6587 mDispatcher->notifyMotion(&motionArgs);
6588 window->assertNoEvents();
6589
6590 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006591 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6593
6594 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6595 mDispatcher->notifyKey(&keyArgs);
6596 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6597
6598 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6599 ADISPLAY_ID_DEFAULT);
6600 mDispatcher->notifyMotion(&motionArgs);
6601 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6602 window->assertNoEvents();
6603}
6604
6605TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6606 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6607 std::make_shared<FakeApplicationHandle>();
6608 sp<FakeWindowHandle> obscuringWindow =
6609 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6610 ADISPLAY_ID_DEFAULT);
6611 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6612 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006613 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006614 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6615 sp<FakeWindowHandle> window =
6616 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006617 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006618 window->setOwnerInfo(222, 222);
6619 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6620 window->setFocusable(true);
6621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6622 setFocusedWindow(window);
6623 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6624
6625 // With the flag set, window should not get any input
6626 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6627 mDispatcher->notifyKey(&keyArgs);
6628 window->assertNoEvents();
6629
6630 NotifyMotionArgs motionArgs =
6631 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6632 ADISPLAY_ID_DEFAULT);
6633 mDispatcher->notifyMotion(&motionArgs);
6634 window->assertNoEvents();
6635
6636 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006637 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6639
6640 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6641 mDispatcher->notifyKey(&keyArgs);
6642 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6643
6644 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6645 ADISPLAY_ID_DEFAULT);
6646 mDispatcher->notifyMotion(&motionArgs);
6647 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6648 window->assertNoEvents();
6649}
6650
6651TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6652 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6653 std::make_shared<FakeApplicationHandle>();
6654 sp<FakeWindowHandle> obscuringWindow =
6655 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6656 ADISPLAY_ID_DEFAULT);
6657 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6658 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006659 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6661 sp<FakeWindowHandle> window =
6662 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006663 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006664 window->setOwnerInfo(222, 222);
6665 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6666 window->setFocusable(true);
6667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6668 setFocusedWindow(window);
6669 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6670
6671 // With the flag set, window should not get any input
6672 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6673 mDispatcher->notifyKey(&keyArgs);
6674 window->assertNoEvents();
6675
6676 NotifyMotionArgs motionArgs =
6677 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6678 ADISPLAY_ID_DEFAULT);
6679 mDispatcher->notifyMotion(&motionArgs);
6680 window->assertNoEvents();
6681
6682 // When the window is no longer obscured because it went on top, it should get input
6683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6684
6685 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6686 mDispatcher->notifyKey(&keyArgs);
6687 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6688
6689 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6690 ADISPLAY_ID_DEFAULT);
6691 mDispatcher->notifyMotion(&motionArgs);
6692 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6693 window->assertNoEvents();
6694}
6695
Antonio Kantekf16f2832021-09-28 04:39:20 +00006696class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6697protected:
6698 std::shared_ptr<FakeApplicationHandle> mApp;
6699 sp<FakeWindowHandle> mWindow;
6700 sp<FakeWindowHandle> mSecondWindow;
6701
6702 void SetUp() override {
6703 InputDispatcherTest::SetUp();
6704
6705 mApp = std::make_shared<FakeApplicationHandle>();
6706 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6707 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006708 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006709 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6710 mSecondWindow->setFocusable(true);
6711
6712 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006714 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006715
6716 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006717 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
6718 WINDOW_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006719 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6720 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6721 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006722 }
6723
Antonio Kantekea47acb2021-12-23 12:41:25 -08006724 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006725 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006726 mWindow->consumeTouchModeEvent(inTouchMode);
6727 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6728 }
6729};
6730
Antonio Kantek26defcf2022-02-08 01:12:27 +00006731TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006732 const WindowInfo& windowInfo = *mWindow->getInfo();
6733 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6734 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006735}
6736
Antonio Kantek26defcf2022-02-08 01:12:27 +00006737TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6738 const WindowInfo& windowInfo = *mWindow->getInfo();
6739 int32_t ownerPid = windowInfo.ownerPid;
6740 int32_t ownerUid = windowInfo.ownerUid;
6741 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6742 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6743 ownerUid, /* hasPermission */ false));
6744 mWindow->assertNoEvents();
6745 mSecondWindow->assertNoEvents();
6746}
6747
6748TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6749 const WindowInfo& windowInfo = *mWindow->getInfo();
6750 int32_t ownerPid = windowInfo.ownerPid;
6751 int32_t ownerUid = windowInfo.ownerUid;
6752 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6753 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6754 /* hasPermission */ true);
6755}
6756
Antonio Kantekf16f2832021-09-28 04:39:20 +00006757TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006758 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006759 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6760 windowInfo.ownerPid, windowInfo.ownerUid,
6761 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006762 mWindow->assertNoEvents();
6763 mSecondWindow->assertNoEvents();
6764}
6765
Antonio Kantek48710e42022-03-24 14:19:30 -07006766TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6767 // Interact with the window first.
6768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6769 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6770 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6771
6772 // Then remove focus.
6773 mWindow->setFocusable(false);
6774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6775
6776 // Assert that caller can switch touch mode by owning one of the last interacted window.
6777 const WindowInfo& windowInfo = *mWindow->getInfo();
6778 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6779 windowInfo.ownerPid, windowInfo.ownerUid,
6780 /* hasPermission= */ false));
6781}
6782
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006783class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6784public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006785 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006786 std::shared_ptr<FakeApplicationHandle> application =
6787 std::make_shared<FakeApplicationHandle>();
6788 std::string name = "Fake Spy ";
6789 name += std::to_string(mSpyCount++);
6790 sp<FakeWindowHandle> spy =
6791 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006792 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006793 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006794 return spy;
6795 }
6796
6797 sp<FakeWindowHandle> createForeground() {
6798 std::shared_ptr<FakeApplicationHandle> application =
6799 std::make_shared<FakeApplicationHandle>();
6800 sp<FakeWindowHandle> window =
6801 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006802 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006803 return window;
6804 }
6805
6806private:
6807 int mSpyCount{0};
6808};
6809
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006810using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006811/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006812 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6813 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006814TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6815 ScopedSilentDeath _silentDeath;
6816
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006817 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006818 spy->setTrustedOverlay(false);
6819 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6820 ".* not a trusted overlay");
6821}
6822
6823/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006824 * Input injection into a display with a spy window but no foreground windows should succeed.
6825 */
6826TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006827 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6829
6830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6831 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6833 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6834}
6835
6836/**
6837 * Verify the order in which different input windows receive events. The touched foreground window
6838 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6839 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6840 * receive events before ones belows it.
6841 *
6842 * Here, we set up a scenario with four windows in the following Z order from the top:
6843 * spy1, spy2, window, spy3.
6844 * We then inject an event and verify that the foreground "window" receives it first, followed by
6845 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6846 * window.
6847 */
6848TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6849 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006850 auto spy1 = createSpy();
6851 auto spy2 = createSpy();
6852 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006853 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6854 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6855 const size_t numChannels = channels.size();
6856
Michael Wright8e9a8562022-02-09 13:44:29 +00006857 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006858 if (!epollFd.ok()) {
6859 FAIL() << "Failed to create epoll fd";
6860 }
6861
6862 for (size_t i = 0; i < numChannels; i++) {
6863 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6864 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6865 FAIL() << "Failed to add fd to epoll";
6866 }
6867 }
6868
6869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6870 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6872
6873 std::vector<size_t> eventOrder;
6874 std::vector<struct epoll_event> events(numChannels);
6875 for (;;) {
6876 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6877 (100ms).count());
6878 if (nFds < 0) {
6879 FAIL() << "Failed to call epoll_wait";
6880 }
6881 if (nFds == 0) {
6882 break; // epoll_wait timed out
6883 }
6884 for (int i = 0; i < nFds; i++) {
6885 ASSERT_EQ(EPOLLIN, events[i].events);
6886 eventOrder.push_back(events[i].data.u64);
6887 channels[i]->consumeMotionDown();
6888 }
6889 }
6890
6891 // Verify the order in which the events were received.
6892 EXPECT_EQ(3u, eventOrder.size());
6893 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6894 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6895 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6896}
6897
6898/**
6899 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6900 */
6901TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6902 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006903 auto spy = createSpy();
6904 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6906
6907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6908 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6909 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6910 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6911 spy->assertNoEvents();
6912}
6913
6914/**
6915 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6916 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6917 * to the window.
6918 */
6919TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6920 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006921 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006922 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6924
6925 // Inject an event outside the spy window's touchable region.
6926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6927 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6929 window->consumeMotionDown();
6930 spy->assertNoEvents();
6931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6932 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6934 window->consumeMotionUp();
6935 spy->assertNoEvents();
6936
6937 // Inject an event inside the spy window's touchable region.
6938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6940 {5, 10}))
6941 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6942 window->consumeMotionDown();
6943 spy->consumeMotionDown();
6944}
6945
6946/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006947 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006948 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006949 */
6950TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6951 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006952 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006953 auto spy = createSpy();
6954 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006955 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006956 spy->setFrame(Rect{0, 0, 20, 20});
6957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6958
6959 // Inject an event outside the spy window's frame and touchable region.
6960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006961 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6962 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006963 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6964 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006965 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006966}
6967
6968/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006969 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6970 * pointers that are down within its bounds.
6971 */
6972TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6973 auto windowLeft = createForeground();
6974 windowLeft->setFrame({0, 0, 100, 200});
6975 auto windowRight = createForeground();
6976 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006977 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006978 spy->setFrame({0, 0, 200, 200});
6979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6980
6981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6982 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6983 {50, 50}))
6984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6985 windowLeft->consumeMotionDown();
6986 spy->consumeMotionDown();
6987
6988 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006989 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006990 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6991 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6992 .pointer(
6993 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6994 .build();
6995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6996 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6997 InputEventInjectionSync::WAIT_FOR_RESULT))
6998 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6999 windowRight->consumeMotionDown();
7000 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7001}
7002
7003/**
7004 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7005 * the spy should receive the second pointer with ACTION_DOWN.
7006 */
7007TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7008 auto window = createForeground();
7009 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007010 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007011 spyRight->setFrame({100, 0, 200, 200});
7012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7013
7014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7016 {50, 50}))
7017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7018 window->consumeMotionDown();
7019 spyRight->assertNoEvents();
7020
7021 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007022 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007023 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7024 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7025 .pointer(
7026 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7027 .build();
7028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7029 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7030 InputEventInjectionSync::WAIT_FOR_RESULT))
7031 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7032 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7033 spyRight->consumeMotionDown();
7034}
7035
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007036/**
7037 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7038 * windows should be allowed to control split touch.
7039 */
7040TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007041 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007042 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007043 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007044 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007045
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007046 auto window = createForeground();
7047 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007048
7049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7050
7051 // First finger down, no window touched.
7052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7053 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7054 {100, 200}))
7055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7056 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7057 window->assertNoEvents();
7058
7059 // Second finger down on window, the window should receive touch down.
7060 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007061 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007062 .displayId(ADISPLAY_ID_DEFAULT)
7063 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7064 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7065 .x(100)
7066 .y(200))
7067 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7068 .build();
7069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7070 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7071 InputEventInjectionSync::WAIT_FOR_RESULT))
7072 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7073
7074 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7075 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7076}
7077
7078/**
7079 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7080 * do not receive key events.
7081 */
7082TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007083 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007084 spy->setFocusable(false);
7085
7086 auto window = createForeground();
7087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7088 setFocusedWindow(window);
7089 window->consumeFocusEvent(true);
7090
7091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7092 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7093 window->consumeKeyDown(ADISPLAY_ID_NONE);
7094
7095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7096 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7097 window->consumeKeyUp(ADISPLAY_ID_NONE);
7098
7099 spy->assertNoEvents();
7100}
7101
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007102using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7103
7104/**
7105 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7106 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7107 */
7108TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7109 auto window = createForeground();
7110 auto spy1 = createSpy();
7111 auto spy2 = createSpy();
7112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7113
7114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7117 window->consumeMotionDown();
7118 spy1->consumeMotionDown();
7119 spy2->consumeMotionDown();
7120
7121 // Pilfer pointers from the second spy window.
7122 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7123 spy2->assertNoEvents();
7124 spy1->consumeMotionCancel();
7125 window->consumeMotionCancel();
7126
7127 // The rest of the gesture should only be sent to the second spy window.
7128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7129 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7130 ADISPLAY_ID_DEFAULT))
7131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7132 spy2->consumeMotionMove();
7133 spy1->assertNoEvents();
7134 window->assertNoEvents();
7135}
7136
7137/**
7138 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7139 * in the middle of the gesture.
7140 */
7141TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7142 auto window = createForeground();
7143 auto spy = createSpy();
7144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7145
7146 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7147 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7148 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7149 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7150 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7151
7152 window->releaseChannel();
7153
7154 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7155
7156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7157 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7158 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7159 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7160}
7161
7162/**
7163 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7164 * the spy, but not to any other windows.
7165 */
7166TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7167 auto spy = createSpy();
7168 auto window = createForeground();
7169
7170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7171
7172 // First finger down on the window and the spy.
7173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7175 {100, 200}))
7176 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7177 spy->consumeMotionDown();
7178 window->consumeMotionDown();
7179
7180 // Spy window pilfers the pointers.
7181 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7182 window->consumeMotionCancel();
7183
7184 // Second finger down on the window and spy, but the window should not receive the pointer down.
7185 const MotionEvent secondFingerDownEvent =
7186 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7187 .displayId(ADISPLAY_ID_DEFAULT)
7188 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7189 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7190 .x(100)
7191 .y(200))
7192 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7193 .build();
7194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7195 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7196 InputEventInjectionSync::WAIT_FOR_RESULT))
7197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7198
7199 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7200
7201 // Third finger goes down outside all windows, so injection should fail.
7202 const MotionEvent thirdFingerDownEvent =
7203 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7204 .displayId(ADISPLAY_ID_DEFAULT)
7205 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7206 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7207 .x(100)
7208 .y(200))
7209 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7210 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7211 .build();
7212 ASSERT_EQ(InputEventInjectionResult::FAILED,
7213 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7214 InputEventInjectionSync::WAIT_FOR_RESULT))
7215 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7216
7217 spy->assertNoEvents();
7218 window->assertNoEvents();
7219}
7220
7221/**
7222 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7223 */
7224TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7225 auto spy = createSpy();
7226 spy->setFrame(Rect(0, 0, 100, 100));
7227 auto window = createForeground();
7228 window->setFrame(Rect(0, 0, 200, 200));
7229
7230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7231
7232 // First finger down on the window only
7233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7234 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7235 {150, 150}))
7236 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7237 window->consumeMotionDown();
7238
7239 // Second finger down on the spy and window
7240 const MotionEvent secondFingerDownEvent =
7241 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7242 .displayId(ADISPLAY_ID_DEFAULT)
7243 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7244 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7245 .x(150)
7246 .y(150))
7247 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7248 .build();
7249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7250 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7251 InputEventInjectionSync::WAIT_FOR_RESULT))
7252 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7253 spy->consumeMotionDown();
7254 window->consumeMotionPointerDown(1);
7255
7256 // Third finger down on the spy and window
7257 const MotionEvent thirdFingerDownEvent =
7258 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7259 .displayId(ADISPLAY_ID_DEFAULT)
7260 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7261 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7262 .x(150)
7263 .y(150))
7264 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7265 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7266 .build();
7267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7268 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7269 InputEventInjectionSync::WAIT_FOR_RESULT))
7270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7271 spy->consumeMotionPointerDown(1);
7272 window->consumeMotionPointerDown(2);
7273
7274 // Spy window pilfers the pointers.
7275 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7276 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7277 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7278
7279 spy->assertNoEvents();
7280 window->assertNoEvents();
7281}
7282
7283/**
7284 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7285 * other windows should be canceled. If this results in the cancellation of all pointers for some
7286 * window, then that window should receive ACTION_CANCEL.
7287 */
7288TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7289 auto spy = createSpy();
7290 spy->setFrame(Rect(0, 0, 100, 100));
7291 auto window = createForeground();
7292 window->setFrame(Rect(0, 0, 200, 200));
7293
7294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7295
7296 // First finger down on both spy and window
7297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7299 {10, 10}))
7300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7301 window->consumeMotionDown();
7302 spy->consumeMotionDown();
7303
7304 // Second finger down on the spy and window
7305 const MotionEvent secondFingerDownEvent =
7306 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7307 .displayId(ADISPLAY_ID_DEFAULT)
7308 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7309 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7310 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7311 .build();
7312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7313 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7314 InputEventInjectionSync::WAIT_FOR_RESULT))
7315 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7316 spy->consumeMotionPointerDown(1);
7317 window->consumeMotionPointerDown(1);
7318
7319 // Spy window pilfers the pointers.
7320 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7321 window->consumeMotionCancel();
7322
7323 spy->assertNoEvents();
7324 window->assertNoEvents();
7325}
7326
7327/**
7328 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7329 * be sent to other windows
7330 */
7331TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7332 auto spy = createSpy();
7333 spy->setFrame(Rect(0, 0, 100, 100));
7334 auto window = createForeground();
7335 window->setFrame(Rect(0, 0, 200, 200));
7336
7337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7338
7339 // First finger down on both window and spy
7340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7341 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7342 {10, 10}))
7343 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7344 window->consumeMotionDown();
7345 spy->consumeMotionDown();
7346
7347 // Spy window pilfers the pointers.
7348 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7349 window->consumeMotionCancel();
7350
7351 // Second finger down on the window only
7352 const MotionEvent secondFingerDownEvent =
7353 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7354 .displayId(ADISPLAY_ID_DEFAULT)
7355 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7356 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7357 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7358 .x(150)
7359 .y(150))
7360 .build();
7361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7362 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7363 InputEventInjectionSync::WAIT_FOR_RESULT))
7364 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7365 window->consumeMotionDown();
7366 window->assertNoEvents();
7367
7368 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7369 spy->consumeMotionMove();
7370 spy->assertNoEvents();
7371}
7372
Prabir Pradhand65552b2021-10-07 11:23:50 -07007373class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7374public:
7375 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7376 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7377 std::make_shared<FakeApplicationHandle>();
7378 sp<FakeWindowHandle> overlay =
7379 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7380 ADISPLAY_ID_DEFAULT);
7381 overlay->setFocusable(false);
7382 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007383 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007384 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007385 overlay->setTrustedOverlay(true);
7386
7387 std::shared_ptr<FakeApplicationHandle> application =
7388 std::make_shared<FakeApplicationHandle>();
7389 sp<FakeWindowHandle> window =
7390 new FakeWindowHandle(application, mDispatcher, "Application window",
7391 ADISPLAY_ID_DEFAULT);
7392 window->setFocusable(true);
7393 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007394
7395 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7397 setFocusedWindow(window);
7398 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7399 return {std::move(overlay), std::move(window)};
7400 }
7401
7402 void sendFingerEvent(int32_t action) {
7403 NotifyMotionArgs motionArgs =
7404 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7405 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7406 mDispatcher->notifyMotion(&motionArgs);
7407 }
7408
7409 void sendStylusEvent(int32_t action) {
7410 NotifyMotionArgs motionArgs =
7411 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7412 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7413 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7414 mDispatcher->notifyMotion(&motionArgs);
7415 }
7416};
7417
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007418using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7419
7420TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7421 ScopedSilentDeath _silentDeath;
7422
Prabir Pradhand65552b2021-10-07 11:23:50 -07007423 auto [overlay, window] = setupStylusOverlayScenario();
7424 overlay->setTrustedOverlay(false);
7425 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7426 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7427 ".* not a trusted overlay");
7428}
7429
7430TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7431 auto [overlay, window] = setupStylusOverlayScenario();
7432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7433
7434 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7435 overlay->consumeMotionDown();
7436 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7437 overlay->consumeMotionUp();
7438
7439 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7440 window->consumeMotionDown();
7441 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7442 window->consumeMotionUp();
7443
7444 overlay->assertNoEvents();
7445 window->assertNoEvents();
7446}
7447
7448TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7449 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007450 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7452
7453 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7454 overlay->consumeMotionDown();
7455 window->consumeMotionDown();
7456 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7457 overlay->consumeMotionUp();
7458 window->consumeMotionUp();
7459
7460 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7461 window->consumeMotionDown();
7462 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7463 window->consumeMotionUp();
7464
7465 overlay->assertNoEvents();
7466 window->assertNoEvents();
7467}
7468
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007469/**
7470 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7471 * The scenario is as follows:
7472 * - The stylus interceptor overlay is configured as a spy window.
7473 * - The stylus interceptor spy receives the start of a new stylus gesture.
7474 * - It pilfers pointers and then configures itself to no longer be a spy.
7475 * - The stylus interceptor continues to receive the rest of the gesture.
7476 */
7477TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7478 auto [overlay, window] = setupStylusOverlayScenario();
7479 overlay->setSpy(true);
7480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7481
7482 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7483 overlay->consumeMotionDown();
7484 window->consumeMotionDown();
7485
7486 // The interceptor pilfers the pointers.
7487 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7488 window->consumeMotionCancel();
7489
7490 // The interceptor configures itself so that it is no longer a spy.
7491 overlay->setSpy(false);
7492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7493
7494 // It continues to receive the rest of the stylus gesture.
7495 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7496 overlay->consumeMotionMove();
7497 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7498 overlay->consumeMotionUp();
7499
7500 window->assertNoEvents();
7501}
7502
Prabir Pradhan5735a322022-04-11 17:23:34 +00007503struct User {
7504 int32_t mPid;
7505 int32_t mUid;
7506 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7507 std::unique_ptr<InputDispatcher>& mDispatcher;
7508
7509 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7510 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7511
7512 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7513 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7514 ADISPLAY_ID_DEFAULT, {100, 200},
7515 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7516 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7517 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7518 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7519 }
7520
7521 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7522 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7523 InputEventInjectionSync::WAIT_FOR_RESULT,
7524 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7525 mPolicyFlags);
7526 }
7527
7528 sp<FakeWindowHandle> createWindow() const {
7529 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7530 std::make_shared<FakeApplicationHandle>();
7531 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7532 "Owned Window", ADISPLAY_ID_DEFAULT);
7533 window->setOwnerInfo(mPid, mUid);
7534 return window;
7535 }
7536};
7537
7538using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7539
7540TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7541 auto owner = User(mDispatcher, 10, 11);
7542 auto window = owner.createWindow();
7543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7544
7545 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7546 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7547 window->consumeMotionDown();
7548
7549 setFocusedWindow(window);
7550 window->consumeFocusEvent(true);
7551
7552 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7553 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7554 window->consumeKeyDown(ADISPLAY_ID_NONE);
7555}
7556
7557TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7558 auto owner = User(mDispatcher, 10, 11);
7559 auto window = owner.createWindow();
7560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7561
7562 auto rando = User(mDispatcher, 20, 21);
7563 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7564 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7565
7566 setFocusedWindow(window);
7567 window->consumeFocusEvent(true);
7568
7569 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7570 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7571 window->assertNoEvents();
7572}
7573
7574TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7575 auto owner = User(mDispatcher, 10, 11);
7576 auto window = owner.createWindow();
7577 auto spy = owner.createWindow();
7578 spy->setSpy(true);
7579 spy->setTrustedOverlay(true);
7580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7581
7582 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7583 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7584 spy->consumeMotionDown();
7585 window->consumeMotionDown();
7586}
7587
7588TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7589 auto owner = User(mDispatcher, 10, 11);
7590 auto window = owner.createWindow();
7591
7592 auto rando = User(mDispatcher, 20, 21);
7593 auto randosSpy = rando.createWindow();
7594 randosSpy->setSpy(true);
7595 randosSpy->setTrustedOverlay(true);
7596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7597
7598 // The event is targeted at owner's window, so injection should succeed, but the spy should
7599 // not receive the event.
7600 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7601 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7602 randosSpy->assertNoEvents();
7603 window->consumeMotionDown();
7604}
7605
7606TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7607 auto owner = User(mDispatcher, 10, 11);
7608 auto window = owner.createWindow();
7609
7610 auto rando = User(mDispatcher, 20, 21);
7611 auto randosSpy = rando.createWindow();
7612 randosSpy->setSpy(true);
7613 randosSpy->setTrustedOverlay(true);
7614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7615
7616 // A user that has injection permission can inject into any window.
7617 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7618 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7619 ADISPLAY_ID_DEFAULT));
7620 randosSpy->consumeMotionDown();
7621 window->consumeMotionDown();
7622
7623 setFocusedWindow(randosSpy);
7624 randosSpy->consumeFocusEvent(true);
7625
7626 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7627 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7628 window->assertNoEvents();
7629}
7630
7631TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7632 auto owner = User(mDispatcher, 10, 11);
7633 auto window = owner.createWindow();
7634
7635 auto rando = User(mDispatcher, 20, 21);
7636 auto randosWindow = rando.createWindow();
7637 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7638 randosWindow->setWatchOutsideTouch(true);
7639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7640
7641 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7642 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7643 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7644 window->consumeMotionDown();
7645 randosWindow->consumeMotionOutside();
7646}
7647
Garfield Tane84e6f92019-08-29 17:28:41 -07007648} // namespace android::inputdispatcher