blob: 7f21deae5aba9a8bb2c855951db2e78f489026d3 [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 }
Antonio Kanteka042c022022-07-06 16:51:07 -0700503
504 bool isPerDisplayTouchModeEnabled() {
505 // TODO(b/198499018): Make this a regular property once per display touch mode is enabled
506 return false;
507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508};
509
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510// --- InputDispatcherTest ---
511
512class InputDispatcherTest : public testing::Test {
513protected:
514 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700515 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000517 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800519 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800520 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000521 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700522 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
524
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000525 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700526 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700528 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700530
531 /**
532 * Used for debugging when writing the test
533 */
534 void dumpDispatcherState() {
535 std::string dump;
536 mDispatcher->dump(dump);
537 std::stringstream ss(dump);
538 std::string to;
539
540 while (std::getline(ss, to, '\n')) {
541 ALOGE("%s", to.c_str());
542 }
543 }
Vishnu Nair958da932020-08-21 17:12:37 -0700544
chaviw3277faf2021-05-19 16:45:23 -0500545 void setFocusedWindow(const sp<WindowInfoHandle>& window,
546 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700547 FocusRequest request;
548 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000549 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700550 if (focusedWindow) {
551 request.focusedToken = focusedWindow->getToken();
552 }
553 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
554 request.displayId = window->getInfo()->displayId;
555 mDispatcher->setFocusedWindow(request);
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557};
558
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
560 KeyEvent event;
561
562 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800563 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
564 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600565 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
566 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800567 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000568 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
569 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 << "Should reject key events with undefined action.";
571
572 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800573 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
574 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600575 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000577 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
578 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 << "Should reject key events with ACTION_MULTIPLE.";
580}
581
582TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
583 MotionEvent event;
584 PointerProperties pointerProperties[MAX_POINTERS + 1];
585 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800586 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 pointerProperties[i].clear();
588 pointerProperties[i].id = i;
589 pointerCoords[i].clear();
590 }
591
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800592 // Some constants commonly used below
593 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
594 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
595 constexpr int32_t metaState = AMETA_NONE;
596 constexpr MotionClassification classification = MotionClassification::NONE;
597
chaviw9eaa22c2020-07-01 16:21:27 -0700598 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800600 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700601 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
602 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
604 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700605 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800606 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000607 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
608 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 << "Should reject motion events with undefined action.";
610
611 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800612 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800613 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
614 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
615 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
616 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500617 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800618 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000619 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
620 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 << "Should reject motion events with pointer down index too large.";
622
Garfield Tanfbe732e2020-01-24 11:26:14 -0800623 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700624 AMOTION_EVENT_ACTION_POINTER_DOWN |
625 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700626 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
627 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700628 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500629 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800630 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000631 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
632 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 << "Should reject motion events with pointer down index too small.";
634
635 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800636 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800637 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
638 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
639 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
640 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500641 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800642 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000643 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
644 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 << "Should reject motion events with pointer up index too large.";
646
Garfield Tanfbe732e2020-01-24 11:26:14 -0800647 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700648 AMOTION_EVENT_ACTION_POINTER_UP |
649 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700650 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
651 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700652 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500653 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800654 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000655 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
656 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 << "Should reject motion events with pointer up index too small.";
658
659 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800660 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
661 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700662 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700663 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
664 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700665 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000667 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
668 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 << "Should reject motion events with 0 pointers.";
670
Garfield Tanfbe732e2020-01-24 11:26:14 -0800671 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
672 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700673 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700674 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
675 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700676 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000678 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
679 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 << "Should reject motion events with more than MAX_POINTERS pointers.";
681
682 // Rejects motion events with invalid pointer ids.
683 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800684 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
685 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700686 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700687 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
688 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700689 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800690 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000691 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
692 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 << "Should reject motion events with pointer ids less than 0.";
694
695 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800696 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
697 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700698 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700699 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
700 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700701 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800702 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000703 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
704 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
706
707 // Rejects motion events with duplicate pointer ids.
708 pointerProperties[0].id = 1;
709 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800710 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
711 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700712 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700713 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
714 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700715 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800716 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000717 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
718 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 << "Should reject motion events with duplicate pointer ids.";
720}
721
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800722/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
723
724TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
725 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800726 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800727 mDispatcher->notifyConfigurationChanged(&args);
728 ASSERT_TRUE(mDispatcher->waitForIdle());
729
730 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
731}
732
733TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800734 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
735 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800736 mDispatcher->notifySwitch(&args);
737
738 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
739 args.policyFlags |= POLICY_FLAG_TRUSTED;
740 mFakePolicy->assertNotifySwitchWasCalled(args);
741}
742
Arthur Hungb92218b2018-08-14 12:00:21 +0800743// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700744static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700745// Default input dispatching timeout if there is no focused application or paused window
746// from which to determine an appropriate dispatching timeout.
747static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
748 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
749 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800750
751class FakeApplicationHandle : public InputApplicationHandle {
752public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700753 FakeApplicationHandle() {
754 mInfo.name = "Fake Application";
755 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500756 mInfo.dispatchingTimeoutMillis =
757 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700758 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800759 virtual ~FakeApplicationHandle() {}
760
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000761 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700762
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500763 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
764 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700765 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800766};
767
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800768class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800769public:
Garfield Tan15601662020-09-22 15:32:38 -0700770 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800771 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700772 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800773 }
774
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800775 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700776 InputEvent* event;
777 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
778 if (!consumeSeq) {
779 return nullptr;
780 }
781 finishEvent(*consumeSeq);
782 return event;
783 }
784
785 /**
786 * Receive an event without acknowledging it.
787 * Return the sequence number that could later be used to send finished signal.
788 */
789 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800790 uint32_t consumeSeq;
791 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800792
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800793 std::chrono::time_point start = std::chrono::steady_clock::now();
794 status_t status = WOULD_BLOCK;
795 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800796 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800797 &event);
798 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
799 if (elapsed > 100ms) {
800 break;
801 }
802 }
803
804 if (status == WOULD_BLOCK) {
805 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700806 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800807 }
808
809 if (status != OK) {
810 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700811 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800812 }
813 if (event == nullptr) {
814 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700815 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700817 if (outEvent != nullptr) {
818 *outEvent = event;
819 }
820 return consumeSeq;
821 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800822
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700823 /**
824 * To be used together with "receiveEvent" to complete the consumption of an event.
825 */
826 void finishEvent(uint32_t consumeSeq) {
827 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
828 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800829 }
830
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000831 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
832 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
833 ASSERT_EQ(OK, status);
834 }
835
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000836 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
837 std::optional<int32_t> expectedDisplayId,
838 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800839 InputEvent* event = consume();
840
841 ASSERT_NE(nullptr, event) << mName.c_str()
842 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800843 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700844 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800845 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800846
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000847 if (expectedDisplayId.has_value()) {
848 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
849 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800850
Tiger Huang8664f8c2018-10-11 19:14:35 +0800851 switch (expectedEventType) {
852 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800853 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
854 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000855 if (expectedFlags.has_value()) {
856 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
857 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800858 break;
859 }
860 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800861 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000862 assertMotionAction(expectedAction, motionEvent.getAction());
863
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000864 if (expectedFlags.has_value()) {
865 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
866 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800867 break;
868 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100869 case AINPUT_EVENT_TYPE_FOCUS: {
870 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
871 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800872 case AINPUT_EVENT_TYPE_CAPTURE: {
873 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
874 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000875 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
876 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
877 }
arthurhungb89ccb02020-12-30 16:19:01 +0800878 case AINPUT_EVENT_TYPE_DRAG: {
879 FAIL() << "Use 'consumeDragEvent' for DRAG events";
880 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800881 default: {
882 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
883 }
884 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800885 }
886
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100887 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
888 InputEvent* event = consume();
889 ASSERT_NE(nullptr, event) << mName.c_str()
890 << ": consumer should have returned non-NULL event.";
891 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
892 << "Got " << inputEventTypeToString(event->getType())
893 << " event instead of FOCUS event";
894
895 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
896 << mName.c_str() << ": event displayId should always be NONE.";
897
898 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
899 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100900 }
901
Prabir Pradhan99987712020-11-10 18:43:05 -0800902 void consumeCaptureEvent(bool hasCapture) {
903 const InputEvent* event = consume();
904 ASSERT_NE(nullptr, event) << mName.c_str()
905 << ": consumer should have returned non-NULL event.";
906 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
907 << "Got " << inputEventTypeToString(event->getType())
908 << " event instead of CAPTURE event";
909
910 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
911 << mName.c_str() << ": event displayId should always be NONE.";
912
913 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
914 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
915 }
916
arthurhungb89ccb02020-12-30 16:19:01 +0800917 void consumeDragEvent(bool isExiting, float x, float y) {
918 const InputEvent* event = consume();
919 ASSERT_NE(nullptr, event) << mName.c_str()
920 << ": consumer should have returned non-NULL event.";
921 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
922 << "Got " << inputEventTypeToString(event->getType())
923 << " event instead of DRAG event";
924
925 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
926 << mName.c_str() << ": event displayId should always be NONE.";
927
928 const auto& dragEvent = static_cast<const DragEvent&>(*event);
929 EXPECT_EQ(isExiting, dragEvent.isExiting());
930 EXPECT_EQ(x, dragEvent.getX());
931 EXPECT_EQ(y, dragEvent.getY());
932 }
933
Antonio Kantekf16f2832021-09-28 04:39:20 +0000934 void consumeTouchModeEvent(bool inTouchMode) {
935 const InputEvent* event = consume();
936 ASSERT_NE(nullptr, event) << mName.c_str()
937 << ": consumer should have returned non-NULL event.";
938 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
939 << "Got " << inputEventTypeToString(event->getType())
940 << " event instead of TOUCH_MODE event";
941
942 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
943 << mName.c_str() << ": event displayId should always be NONE.";
944 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
945 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
946 }
947
chaviwd1c23182019-12-20 18:44:56 -0800948 void assertNoEvents() {
949 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 if (event == nullptr) {
951 return;
952 }
953 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
954 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
955 ADD_FAILURE() << "Received key event "
956 << KeyEvent::actionToString(keyEvent.getAction());
957 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
958 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
959 ADD_FAILURE() << "Received motion event "
960 << MotionEvent::actionToString(motionEvent.getAction());
961 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
962 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
963 ADD_FAILURE() << "Received focus event, hasFocus = "
964 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800965 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
966 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
967 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
968 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000969 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
970 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
971 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
972 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 }
974 FAIL() << mName.c_str()
975 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800976 }
977
978 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
979
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800980 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
981
chaviwd1c23182019-12-20 18:44:56 -0800982protected:
983 std::unique_ptr<InputConsumer> mConsumer;
984 PreallocatedInputEventFactory mEventFactory;
985
986 std::string mName;
987};
988
chaviw3277faf2021-05-19 16:45:23 -0500989class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800990public:
991 static const int32_t WIDTH = 600;
992 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800993
Chris Yea209fde2020-07-22 13:54:51 -0700994 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700995 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500996 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800997 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500998 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700999 base::Result<std::unique_ptr<InputChannel>> channel =
1000 dispatcher->createInputChannel(name);
1001 token = (*channel)->getConnectionToken();
1002 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001003 }
1004
1005 inputApplicationHandle->updateInfo();
1006 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1007
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001008 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001009 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001010 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001011 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001012 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001013 mInfo.frameLeft = 0;
1014 mInfo.frameTop = 0;
1015 mInfo.frameRight = WIDTH;
1016 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001017 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001018 mInfo.globalScaleFactor = 1.0;
1019 mInfo.touchableRegion.clear();
1020 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001021 mInfo.ownerPid = WINDOW_PID;
1022 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001023 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001024 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001025 }
1026
Arthur Hungabbb9d82021-09-01 14:52:30 +00001027 sp<FakeWindowHandle> clone(
1028 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001029 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001030 sp<FakeWindowHandle> handle =
1031 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1032 displayId, mInfo.token);
1033 return handle;
1034 }
1035
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001036 void setTouchable(bool touchable) {
1037 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1038 }
chaviwd1c23182019-12-20 18:44:56 -08001039
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001040 void setFocusable(bool focusable) {
1041 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1042 }
1043
1044 void setVisible(bool visible) {
1045 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1046 }
Vishnu Nair958da932020-08-21 17:12:37 -07001047
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001048 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001049 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001050 }
1051
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001052 void setPaused(bool paused) {
1053 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1054 }
1055
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001056 void setPreventSplitting(bool preventSplitting) {
1057 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001058 }
1059
1060 void setSlippery(bool slippery) {
1061 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1062 }
1063
1064 void setWatchOutsideTouch(bool watchOutside) {
1065 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1066 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001068 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1069
1070 void setInterceptsStylus(bool interceptsStylus) {
1071 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1072 }
1073
1074 void setDropInput(bool dropInput) {
1075 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1076 }
1077
1078 void setDropInputIfObscured(bool dropInputIfObscured) {
1079 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1080 }
1081
1082 void setNoInputChannel(bool noInputChannel) {
1083 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1084 }
1085
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001086 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1087
chaviw3277faf2021-05-19 16:45:23 -05001088 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001089
Bernardo Rufino7393d172021-02-26 13:56:11 +00001090 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1091
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001092 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001093 mInfo.frameLeft = frame.left;
1094 mInfo.frameTop = frame.top;
1095 mInfo.frameRight = frame.right;
1096 mInfo.frameBottom = frame.bottom;
1097 mInfo.touchableRegion.clear();
1098 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001099
1100 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1101 ui::Transform translate;
1102 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1103 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001104 }
1105
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001106 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1107
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001108 void setIsWallpaper(bool isWallpaper) {
1109 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1110 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001111
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001112 void setDupTouchToWallpaper(bool hasWallpaper) {
1113 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1114 }
chaviwd1c23182019-12-20 18:44:56 -08001115
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001116 void setTrustedOverlay(bool trustedOverlay) {
1117 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1118 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001119
chaviw9eaa22c2020-07-01 16:21:27 -07001120 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1121 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1122 }
1123
1124 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001125
yunho.shinf4a80b82020-11-16 21:13:57 +09001126 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1127
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001128 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1129 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1130 expectedFlags);
1131 }
1132
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001133 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1134 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1135 }
1136
Svet Ganov5d3bc372020-01-26 23:11:07 -08001137 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001138 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001139 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1140 expectedFlags);
1141 }
1142
1143 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001145 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1146 expectedFlags);
1147 }
1148
1149 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001150 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001151 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1152 }
1153
1154 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1155 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001156 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1157 expectedFlags);
1158 }
1159
Svet Ganov5d3bc372020-01-26 23:11:07 -08001160 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001161 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1162 int32_t expectedFlags = 0) {
1163 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1164 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001165 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1166 }
1167
1168 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001169 int32_t expectedFlags = 0) {
1170 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1171 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001172 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1173 }
1174
1175 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001176 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001177 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1178 expectedFlags);
1179 }
1180
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001181 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1182 int32_t expectedFlags = 0) {
1183 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1184 expectedFlags);
1185 }
1186
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001187 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1188 int32_t expectedFlags = 0) {
1189 InputEvent* event = consume();
1190 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1191 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1192 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1193 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1194 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1195 }
1196
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001197 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1198 ASSERT_NE(mInputReceiver, nullptr)
1199 << "Cannot consume events from a window with no receiver";
1200 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1201 }
1202
Prabir Pradhan99987712020-11-10 18:43:05 -08001203 void consumeCaptureEvent(bool hasCapture) {
1204 ASSERT_NE(mInputReceiver, nullptr)
1205 << "Cannot consume events from a window with no receiver";
1206 mInputReceiver->consumeCaptureEvent(hasCapture);
1207 }
1208
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001209 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1210 std::optional<int32_t> expectedDisplayId,
1211 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001212 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1213 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1214 expectedFlags);
1215 }
1216
arthurhungb89ccb02020-12-30 16:19:01 +08001217 void consumeDragEvent(bool isExiting, float x, float y) {
1218 mInputReceiver->consumeDragEvent(isExiting, x, y);
1219 }
1220
Antonio Kantekf16f2832021-09-28 04:39:20 +00001221 void consumeTouchModeEvent(bool inTouchMode) {
1222 ASSERT_NE(mInputReceiver, nullptr)
1223 << "Cannot consume events from a window with no receiver";
1224 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1225 }
1226
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001227 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001228 if (mInputReceiver == nullptr) {
1229 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1230 return std::nullopt;
1231 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001232 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001233 }
1234
1235 void finishEvent(uint32_t sequenceNum) {
1236 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1237 mInputReceiver->finishEvent(sequenceNum);
1238 }
1239
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001240 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1241 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1242 mInputReceiver->sendTimeline(inputEventId, timeline);
1243 }
1244
chaviwaf87b3e2019-10-01 16:59:28 -07001245 InputEvent* consume() {
1246 if (mInputReceiver == nullptr) {
1247 return nullptr;
1248 }
1249 return mInputReceiver->consume();
1250 }
1251
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001252 MotionEvent* consumeMotion() {
1253 InputEvent* event = consume();
1254 if (event == nullptr) {
1255 ADD_FAILURE() << "Consume failed : no event";
1256 return nullptr;
1257 }
1258 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1259 ADD_FAILURE() << "Instead of motion event, got "
1260 << inputEventTypeToString(event->getType());
1261 return nullptr;
1262 }
1263 return static_cast<MotionEvent*>(event);
1264 }
1265
Arthur Hungb92218b2018-08-14 12:00:21 +08001266 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001267 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001268 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001269 return; // Can't receive events if the window does not have input channel
1270 }
1271 ASSERT_NE(nullptr, mInputReceiver)
1272 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001273 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001274 }
1275
chaviwaf87b3e2019-10-01 16:59:28 -07001276 sp<IBinder> getToken() { return mInfo.token; }
1277
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001278 const std::string& getName() { return mName; }
1279
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001280 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1281 mInfo.ownerPid = ownerPid;
1282 mInfo.ownerUid = ownerUid;
1283 }
1284
Prabir Pradhanedd96402022-02-15 01:46:16 -08001285 int32_t getPid() const { return mInfo.ownerPid; }
1286
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001287 void destroyReceiver() { mInputReceiver = nullptr; }
1288
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001289 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1290
chaviwd1c23182019-12-20 18:44:56 -08001291private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001292 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001293 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001294 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001295};
1296
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001297std::atomic<int32_t> FakeWindowHandle::sId{1};
1298
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001299static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001300 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001301 int32_t displayId = ADISPLAY_ID_NONE,
1302 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001303 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001304 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1305 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001306 KeyEvent event;
1307 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1308
1309 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001310 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001311 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1312 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001313
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001314 if (!allowKeyRepeat) {
1315 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1316 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001317 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001318 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001319}
1320
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001321static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001322 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001323 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1324}
1325
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001326// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1327// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1328// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001329static InputEventInjectionResult injectKeyDownNoRepeat(
1330 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001331 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1332 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1333 /* allowKeyRepeat */ false);
1334}
1335
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001336static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001337 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001338 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1339}
1340
Garfield Tandf26e862020-07-01 20:18:19 -07001341class PointerBuilder {
1342public:
1343 PointerBuilder(int32_t id, int32_t toolType) {
1344 mProperties.clear();
1345 mProperties.id = id;
1346 mProperties.toolType = toolType;
1347 mCoords.clear();
1348 }
1349
1350 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1351
1352 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1353
1354 PointerBuilder& axis(int32_t axis, float value) {
1355 mCoords.setAxisValue(axis, value);
1356 return *this;
1357 }
1358
1359 PointerProperties buildProperties() const { return mProperties; }
1360
1361 PointerCoords buildCoords() const { return mCoords; }
1362
1363private:
1364 PointerProperties mProperties;
1365 PointerCoords mCoords;
1366};
1367
1368class MotionEventBuilder {
1369public:
1370 MotionEventBuilder(int32_t action, int32_t source) {
1371 mAction = action;
1372 mSource = source;
1373 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1374 }
1375
1376 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1377 mEventTime = eventTime;
1378 return *this;
1379 }
1380
1381 MotionEventBuilder& displayId(int32_t displayId) {
1382 mDisplayId = displayId;
1383 return *this;
1384 }
1385
1386 MotionEventBuilder& actionButton(int32_t actionButton) {
1387 mActionButton = actionButton;
1388 return *this;
1389 }
1390
arthurhung6d4bed92021-03-17 11:59:33 +08001391 MotionEventBuilder& buttonState(int32_t buttonState) {
1392 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001393 return *this;
1394 }
1395
1396 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1397 mRawXCursorPosition = rawXCursorPosition;
1398 return *this;
1399 }
1400
1401 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1402 mRawYCursorPosition = rawYCursorPosition;
1403 return *this;
1404 }
1405
1406 MotionEventBuilder& pointer(PointerBuilder pointer) {
1407 mPointers.push_back(pointer);
1408 return *this;
1409 }
1410
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001411 MotionEventBuilder& addFlag(uint32_t flags) {
1412 mFlags |= flags;
1413 return *this;
1414 }
1415
Garfield Tandf26e862020-07-01 20:18:19 -07001416 MotionEvent build() {
1417 std::vector<PointerProperties> pointerProperties;
1418 std::vector<PointerCoords> pointerCoords;
1419 for (const PointerBuilder& pointer : mPointers) {
1420 pointerProperties.push_back(pointer.buildProperties());
1421 pointerCoords.push_back(pointer.buildCoords());
1422 }
1423
1424 // Set mouse cursor position for the most common cases to avoid boilerplate.
1425 if (mSource == AINPUT_SOURCE_MOUSE &&
1426 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1427 mPointers.size() == 1) {
1428 mRawXCursorPosition = pointerCoords[0].getX();
1429 mRawYCursorPosition = pointerCoords[0].getY();
1430 }
1431
1432 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001433 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001434 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001435 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001436 mButtonState, MotionClassification::NONE, identityTransform,
1437 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001438 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1439 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001440
1441 return event;
1442 }
1443
1444private:
1445 int32_t mAction;
1446 int32_t mSource;
1447 nsecs_t mEventTime;
1448 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1449 int32_t mActionButton{0};
1450 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001451 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001452 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1453 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1454
1455 std::vector<PointerBuilder> mPointers;
1456};
1457
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001458static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001459 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001460 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001461 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1462 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1463 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1464 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001465}
1466
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001468 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001469 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001470 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001471 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1472 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001473 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001474 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1475 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001476 MotionEvent event = MotionEventBuilder(action, source)
1477 .displayId(displayId)
1478 .eventTime(eventTime)
1479 .rawXCursorPosition(cursorPosition.x)
1480 .rawYCursorPosition(cursorPosition.y)
1481 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1482 .x(position.x)
1483 .y(position.y))
1484 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001485
1486 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001487 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1488 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001489}
1490
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001491static InputEventInjectionResult injectMotionDown(
1492 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1493 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001494 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001495}
1496
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001497static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001498 int32_t source, int32_t displayId,
1499 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001500 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001501}
1502
Jackal Guof9696682018-10-05 12:23:23 +08001503static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1504 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1505 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1507 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1508 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001509
1510 return args;
1511}
1512
chaviwd1c23182019-12-20 18:44:56 -08001513static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1514 const std::vector<PointF>& points) {
1515 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001516 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1517 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1518 }
1519
chaviwd1c23182019-12-20 18:44:56 -08001520 PointerProperties pointerProperties[pointerCount];
1521 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001522
chaviwd1c23182019-12-20 18:44:56 -08001523 for (size_t i = 0; i < pointerCount; i++) {
1524 pointerProperties[i].clear();
1525 pointerProperties[i].id = i;
1526 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001527
chaviwd1c23182019-12-20 18:44:56 -08001528 pointerCoords[i].clear();
1529 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1530 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1531 }
Jackal Guof9696682018-10-05 12:23:23 +08001532
1533 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1534 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001535 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001536 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1537 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001538 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1539 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001540 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1541 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001542
1543 return args;
1544}
1545
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001546static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1547 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1548}
1549
chaviwd1c23182019-12-20 18:44:56 -08001550static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1551 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1552}
1553
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001554static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1555 const PointerCaptureRequest& request) {
1556 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001557}
1558
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001559/**
1560 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1561 * broken channel.
1562 */
1563TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1565 sp<FakeWindowHandle> window =
1566 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1567 ADISPLAY_ID_DEFAULT);
1568
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1570
1571 // Window closes its channel, but the window remains.
1572 window->destroyReceiver();
1573 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1574}
1575
Arthur Hungb92218b2018-08-14 12:00:21 +08001576TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001577 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001578 sp<FakeWindowHandle> window =
1579 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001580
Arthur Hung72d8dc32020-03-28 00:48:39 +00001581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001585
1586 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001587 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001588}
1589
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001590TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1591 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1592 sp<FakeWindowHandle> window =
1593 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1594
1595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1596 // Inject a MotionEvent to an unknown display.
1597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1600
1601 // Window should receive motion event.
1602 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1603}
1604
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001605/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001606 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001607 * This test serves as a sanity check for the next test, where setInputWindows is
1608 * called twice.
1609 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001610TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001611 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612 sp<FakeWindowHandle> window =
1613 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1614 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1619 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001621
1622 // Window should receive motion event.
1623 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1624}
1625
1626/**
1627 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001628 */
1629TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001630 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001631 sp<FakeWindowHandle> window =
1632 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1633 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001634
1635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001638 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1639 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001641
1642 // Window should receive motion event.
1643 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1644}
1645
Arthur Hungb92218b2018-08-14 12:00:21 +08001646// The foreground window should receive the first touch down event.
1647TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001649 sp<FakeWindowHandle> windowTop =
1650 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1651 sp<FakeWindowHandle> windowSecond =
1652 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001653
Arthur Hung72d8dc32020-03-28 00:48:39 +00001654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1657 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001658
1659 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001660 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001661 windowSecond->assertNoEvents();
1662}
1663
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001664/**
1665 * Two windows: A top window, and a wallpaper behind the window.
1666 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1667 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001668 * 1. foregroundWindow <-- dup touch to wallpaper
1669 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001670 */
1671TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1672 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1673 sp<FakeWindowHandle> foregroundWindow =
1674 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001675 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001676 sp<FakeWindowHandle> wallpaperWindow =
1677 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001678 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001679 constexpr int expectedWallpaperFlags =
1680 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1681
1682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1684 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1685 {100, 200}))
1686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1687
1688 // Both foreground window and its wallpaper should receive the touch down
1689 foregroundWindow->consumeMotionDown();
1690 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1691
1692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1693 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1694 ADISPLAY_ID_DEFAULT, {110, 200}))
1695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1696
1697 foregroundWindow->consumeMotionMove();
1698 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1699
1700 // Now the foreground window goes away, but the wallpaper stays
1701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1702 foregroundWindow->consumeMotionCancel();
1703 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1704 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1705}
1706
1707/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001708 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1709 * with the following differences:
1710 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1711 * clean up the connection.
1712 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1713 * Ensure that there's no crash in the dispatcher.
1714 */
1715TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1716 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1717 sp<FakeWindowHandle> foregroundWindow =
1718 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001719 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001720 sp<FakeWindowHandle> wallpaperWindow =
1721 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001722 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001723 constexpr int expectedWallpaperFlags =
1724 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1725
1726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1729 {100, 200}))
1730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1731
1732 // Both foreground window and its wallpaper should receive the touch down
1733 foregroundWindow->consumeMotionDown();
1734 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1735
1736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1737 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1738 ADISPLAY_ID_DEFAULT, {110, 200}))
1739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1740
1741 foregroundWindow->consumeMotionMove();
1742 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1743
1744 // Wallpaper closes its channel, but the window remains.
1745 wallpaperWindow->destroyReceiver();
1746 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1747
1748 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1749 // is no longer valid.
1750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1751 foregroundWindow->consumeMotionCancel();
1752}
1753
1754/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001755 * A single window that receives touch (on top), and a wallpaper window underneath it.
1756 * The top window gets a multitouch gesture.
1757 * Ensure that wallpaper gets the same gesture.
1758 */
1759TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1761 sp<FakeWindowHandle> window =
1762 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001763 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001764
1765 sp<FakeWindowHandle> wallpaperWindow =
1766 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001767 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001768 constexpr int expectedWallpaperFlags =
1769 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1770
1771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1772
1773 // Touch down on top window
1774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1776 {100, 100}))
1777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1778
1779 // Both top window and its wallpaper should receive the touch down
1780 window->consumeMotionDown();
1781 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1782
1783 // Second finger down on the top window
1784 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001785 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001786 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1787 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1788 .x(100)
1789 .y(100))
1790 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1791 .x(150)
1792 .y(150))
1793 .build();
1794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1795 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1796 InputEventInjectionSync::WAIT_FOR_RESULT))
1797 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1798
1799 window->consumeMotionPointerDown(1 /* pointerIndex */);
1800 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1801 expectedWallpaperFlags);
1802 window->assertNoEvents();
1803 wallpaperWindow->assertNoEvents();
1804}
1805
1806/**
1807 * Two windows: a window on the left and window on the right.
1808 * A third window, wallpaper, is behind both windows, and spans both top windows.
1809 * The first touch down goes to the left window. A second pointer touches down on the right window.
1810 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1811 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1812 * ACTION_POINTER_DOWN(1).
1813 */
1814TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1815 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1816 sp<FakeWindowHandle> leftWindow =
1817 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1818 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001819 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001820
1821 sp<FakeWindowHandle> rightWindow =
1822 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1823 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001824 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001825
1826 sp<FakeWindowHandle> wallpaperWindow =
1827 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1828 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001829 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001830 constexpr int expectedWallpaperFlags =
1831 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1832
1833 mDispatcher->setInputWindows(
1834 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1835
1836 // Touch down on left window
1837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1839 {100, 100}))
1840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1841
1842 // Both foreground window and its wallpaper should receive the touch down
1843 leftWindow->consumeMotionDown();
1844 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1845
1846 // Second finger down on the right window
1847 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001848 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001849 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1850 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1851 .x(100)
1852 .y(100))
1853 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1854 .x(300)
1855 .y(100))
1856 .build();
1857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1858 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1859 InputEventInjectionSync::WAIT_FOR_RESULT))
1860 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1861
1862 leftWindow->consumeMotionMove();
1863 // Since the touch is split, right window gets ACTION_DOWN
1864 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1865 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1866 expectedWallpaperFlags);
1867
1868 // Now, leftWindow, which received the first finger, disappears.
1869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1870 leftWindow->consumeMotionCancel();
1871 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1872 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1873
1874 // The pointer that's still down on the right window moves, and goes to the right window only.
1875 // As far as the dispatcher's concerned though, both pointers are still present.
1876 const MotionEvent secondFingerMoveEvent =
1877 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1878 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1879 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1880 .x(100)
1881 .y(100))
1882 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1883 .x(310)
1884 .y(110))
1885 .build();
1886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1887 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1888 InputEventInjectionSync::WAIT_FOR_RESULT));
1889 rightWindow->consumeMotionMove();
1890
1891 leftWindow->assertNoEvents();
1892 rightWindow->assertNoEvents();
1893 wallpaperWindow->assertNoEvents();
1894}
1895
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001896/**
1897 * On the display, have a single window, and also an area where there's no window.
1898 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1899 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1900 */
1901TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1902 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1903 sp<FakeWindowHandle> window =
1904 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1905
1906 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1907 NotifyMotionArgs args;
1908
1909 // Touch down on the empty space
1910 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1911
1912 mDispatcher->waitForIdle();
1913 window->assertNoEvents();
1914
1915 // Now touch down on the window with another pointer
1916 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1917 mDispatcher->waitForIdle();
1918 window->consumeMotionDown();
1919}
1920
1921/**
1922 * Same test as above, but instead of touching the empty space, the first touch goes to
1923 * non-touchable window.
1924 */
1925TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1927 sp<FakeWindowHandle> window1 =
1928 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1929 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1930 window1->setTouchable(false);
1931 sp<FakeWindowHandle> window2 =
1932 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1933 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1934
1935 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1936
1937 NotifyMotionArgs args;
1938 // Touch down on the non-touchable window
1939 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1940
1941 mDispatcher->waitForIdle();
1942 window1->assertNoEvents();
1943 window2->assertNoEvents();
1944
1945 // Now touch down on the window with another pointer
1946 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1947 mDispatcher->waitForIdle();
1948 window2->consumeMotionDown();
1949}
1950
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001951/**
1952 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
1953 * to the event time of the first ACTION_DOWN sent to the particular window.
1954 */
1955TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
1956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1957 sp<FakeWindowHandle> window1 =
1958 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1959 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1960 sp<FakeWindowHandle> window2 =
1961 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1962 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1963
1964 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1965
1966 NotifyMotionArgs args;
1967 // Touch down on the first window
1968 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1969
1970 mDispatcher->waitForIdle();
1971 InputEvent* inputEvent1 = window1->consume();
1972 window2->assertNoEvents();
1973 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
1974 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
1975 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
1976
1977 // Now touch down on the window with another pointer
1978 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1979 mDispatcher->waitForIdle();
1980 InputEvent* inputEvent2 = window2->consume();
1981 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
1982 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
1983 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
1984 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
1985
1986 // Now move the pointer on the second window
1987 mDispatcher->notifyMotion(
1988 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
1989 mDispatcher->waitForIdle();
1990 InputEvent* inputEvent3 = window2->consume();
1991 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
1992 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
1993
1994 // Now add new touch down on the second window
1995 mDispatcher->notifyMotion(
1996 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
1997 mDispatcher->waitForIdle();
1998 InputEvent* inputEvent4 = window2->consume();
1999 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
2000 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
2001
2002 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2003 window1->consumeMotionMove();
2004 window1->assertNoEvents();
2005
2006 // Now move the pointer on the first window
2007 mDispatcher->notifyMotion(
2008 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2009 mDispatcher->waitForIdle();
2010 InputEvent* inputEvent5 = window1->consume();
2011 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2012 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2013
2014 mDispatcher->notifyMotion(&(
2015 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2016 mDispatcher->waitForIdle();
2017 InputEvent* inputEvent6 = window1->consume();
2018 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2019 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2020}
2021
Garfield Tandf26e862020-07-01 20:18:19 -07002022TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002023 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002024 sp<FakeWindowHandle> windowLeft =
2025 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2026 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002027 sp<FakeWindowHandle> windowRight =
2028 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2029 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002030
2031 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2032
2033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2034
2035 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002037 injectMotionEvent(mDispatcher,
2038 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2039 AINPUT_SOURCE_MOUSE)
2040 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2041 .x(900)
2042 .y(400))
2043 .build()));
2044 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2045 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2046 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2047 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2048
2049 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002051 injectMotionEvent(mDispatcher,
2052 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2053 AINPUT_SOURCE_MOUSE)
2054 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2055 .x(300)
2056 .y(400))
2057 .build()));
2058 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2059 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2060 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2061 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2062 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2063 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2064
2065 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002067 injectMotionEvent(mDispatcher,
2068 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2069 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2070 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2071 .x(300)
2072 .y(400))
2073 .build()));
2074 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2075
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002077 injectMotionEvent(mDispatcher,
2078 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2079 AINPUT_SOURCE_MOUSE)
2080 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2081 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2082 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2083 .x(300)
2084 .y(400))
2085 .build()));
2086 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2087 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2088
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002090 injectMotionEvent(mDispatcher,
2091 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2092 AINPUT_SOURCE_MOUSE)
2093 .buttonState(0)
2094 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2095 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2096 .x(300)
2097 .y(400))
2098 .build()));
2099 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2100 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002103 injectMotionEvent(mDispatcher,
2104 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2105 .buttonState(0)
2106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2107 .x(300)
2108 .y(400))
2109 .build()));
2110 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2111
2112 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002114 injectMotionEvent(mDispatcher,
2115 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2116 AINPUT_SOURCE_MOUSE)
2117 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2118 .x(900)
2119 .y(400))
2120 .build()));
2121 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2122 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2123 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2124 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2125 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2126 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2127}
2128
2129// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2130// directly in this test.
2131TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002132 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002133 sp<FakeWindowHandle> window =
2134 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2135 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002136
2137 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2138
2139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2140
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002142 injectMotionEvent(mDispatcher,
2143 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2144 AINPUT_SOURCE_MOUSE)
2145 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2146 .x(300)
2147 .y(400))
2148 .build()));
2149 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2150 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2151
2152 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002154 injectMotionEvent(mDispatcher,
2155 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2156 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2157 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2158 .x(300)
2159 .y(400))
2160 .build()));
2161 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2162
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002164 injectMotionEvent(mDispatcher,
2165 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2166 AINPUT_SOURCE_MOUSE)
2167 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2168 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2169 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2170 .x(300)
2171 .y(400))
2172 .build()));
2173 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2174 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2175
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002177 injectMotionEvent(mDispatcher,
2178 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2179 AINPUT_SOURCE_MOUSE)
2180 .buttonState(0)
2181 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2182 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2183 .x(300)
2184 .y(400))
2185 .build()));
2186 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2187 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2188
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002189 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002190 injectMotionEvent(mDispatcher,
2191 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2192 .buttonState(0)
2193 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2194 .x(300)
2195 .y(400))
2196 .build()));
2197 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2198
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002200 injectMotionEvent(mDispatcher,
2201 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2202 AINPUT_SOURCE_MOUSE)
2203 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2204 .x(300)
2205 .y(400))
2206 .build()));
2207 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2208 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2209}
2210
Garfield Tan00f511d2019-06-12 16:55:40 -07002211TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002213
2214 sp<FakeWindowHandle> windowLeft =
2215 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2216 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002217 sp<FakeWindowHandle> windowRight =
2218 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2219 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002220
2221 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2222
Arthur Hung72d8dc32020-03-28 00:48:39 +00002223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002224
2225 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2226 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002228 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002229 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002230 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002231 windowRight->assertNoEvents();
2232}
2233
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002234TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002235 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002236 sp<FakeWindowHandle> window =
2237 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002238 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002239
Arthur Hung72d8dc32020-03-28 00:48:39 +00002240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002241 setFocusedWindow(window);
2242
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002243 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002244
2245 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2246 mDispatcher->notifyKey(&keyArgs);
2247
2248 // Window should receive key down event.
2249 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2250
2251 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2252 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002253 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002254 mDispatcher->notifyDeviceReset(&args);
2255 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2256 AKEY_EVENT_FLAG_CANCELED);
2257}
2258
2259TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002261 sp<FakeWindowHandle> window =
2262 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2263
Arthur Hung72d8dc32020-03-28 00:48:39 +00002264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002265
2266 NotifyMotionArgs motionArgs =
2267 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2268 ADISPLAY_ID_DEFAULT);
2269 mDispatcher->notifyMotion(&motionArgs);
2270
2271 // Window should receive motion down event.
2272 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2273
2274 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2275 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002276 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002277 mDispatcher->notifyDeviceReset(&args);
2278 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2279 0 /*expectedFlags*/);
2280}
2281
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002282TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2284 sp<FakeWindowHandle> window =
2285 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2286 window->setFocusable(true);
2287
2288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2289 setFocusedWindow(window);
2290
2291 window->consumeFocusEvent(true);
2292
2293 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2294 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2295 const nsecs_t injectTime = keyArgs.eventTime;
2296 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2297 mDispatcher->notifyKey(&keyArgs);
2298 // The dispatching time should be always greater than or equal to intercept key timeout.
2299 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2300 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2301 std::chrono::nanoseconds(interceptKeyTimeout).count());
2302}
2303
2304TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2305 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2306 sp<FakeWindowHandle> window =
2307 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2308 window->setFocusable(true);
2309
2310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2311 setFocusedWindow(window);
2312
2313 window->consumeFocusEvent(true);
2314
2315 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2316 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2317 mFakePolicy->setInterceptKeyTimeout(150ms);
2318 mDispatcher->notifyKey(&keyDown);
2319 mDispatcher->notifyKey(&keyUp);
2320
2321 // Window should receive key event immediately when same key up.
2322 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2323 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2324}
2325
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002326/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002327 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2328 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2329 * ACTION_OUTSIDE event is sent per gesture.
2330 */
2331TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2332 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2333 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2334 sp<FakeWindowHandle> window =
2335 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2336 window->setWatchOutsideTouch(true);
2337 window->setFrame(Rect{0, 0, 100, 100});
2338 sp<FakeWindowHandle> secondWindow =
2339 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2340 secondWindow->setFrame(Rect{100, 100, 200, 200});
2341 sp<FakeWindowHandle> thirdWindow =
2342 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2343 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2345
2346 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2347 NotifyMotionArgs motionArgs =
2348 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2349 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2350 mDispatcher->notifyMotion(&motionArgs);
2351 window->assertNoEvents();
2352 secondWindow->assertNoEvents();
2353
2354 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2355 // Now, `window` should get ACTION_OUTSIDE.
2356 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2357 {PointF{-10, -10}, PointF{105, 105}});
2358 mDispatcher->notifyMotion(&motionArgs);
2359 window->consumeMotionOutside();
2360 secondWindow->consumeMotionDown();
2361 thirdWindow->assertNoEvents();
2362
2363 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2364 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2365 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2366 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2367 mDispatcher->notifyMotion(&motionArgs);
2368 window->assertNoEvents();
2369 secondWindow->consumeMotionMove();
2370 thirdWindow->consumeMotionDown();
2371}
2372
Prabir Pradhan814fe082022-07-22 20:22:18 +00002373TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2374 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2375 sp<FakeWindowHandle> window =
2376 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2377 window->setFocusable(true);
2378
2379 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2380 setFocusedWindow(window);
2381
2382 window->consumeFocusEvent(true);
2383
2384 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2385 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2386 mDispatcher->notifyKey(&keyDown);
2387 mDispatcher->notifyKey(&keyUp);
2388
2389 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2390 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2391
2392 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2393 mDispatcher->onWindowInfosChanged({}, {});
2394
2395 window->consumeFocusEvent(false);
2396
2397 mDispatcher->notifyKey(&keyDown);
2398 mDispatcher->notifyKey(&keyUp);
2399 window->assertNoEvents();
2400}
2401
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002402/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002403 * Ensure the correct coordinate spaces are used by InputDispatcher.
2404 *
2405 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2406 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2407 * space.
2408 */
2409class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2410public:
2411 void SetUp() override {
2412 InputDispatcherTest::SetUp();
2413 mDisplayInfos.clear();
2414 mWindowInfos.clear();
2415 }
2416
2417 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2418 gui::DisplayInfo info;
2419 info.displayId = displayId;
2420 info.transform = transform;
2421 mDisplayInfos.push_back(std::move(info));
2422 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2423 }
2424
2425 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2426 mWindowInfos.push_back(*windowHandle->getInfo());
2427 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2428 }
2429
2430 // Set up a test scenario where the display has a scaled projection and there are two windows
2431 // on the display.
2432 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2433 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2434 // respectively.
2435 ui::Transform displayTransform;
2436 displayTransform.set(2, 0, 0, 4);
2437 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2438
2439 std::shared_ptr<FakeApplicationHandle> application =
2440 std::make_shared<FakeApplicationHandle>();
2441
2442 // Add two windows to the display. Their frames are represented in the display space.
2443 sp<FakeWindowHandle> firstWindow =
2444 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002445 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2446 addWindow(firstWindow);
2447
2448 sp<FakeWindowHandle> secondWindow =
2449 new FakeWindowHandle(application, mDispatcher, "Second Window",
2450 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002451 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2452 addWindow(secondWindow);
2453 return {std::move(firstWindow), std::move(secondWindow)};
2454 }
2455
2456private:
2457 std::vector<gui::DisplayInfo> mDisplayInfos;
2458 std::vector<gui::WindowInfo> mWindowInfos;
2459};
2460
2461TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2462 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2463 // Send down to the first window. The point is represented in the display space. The point is
2464 // selected so that if the hit test was done with the transform applied to it, then it would
2465 // end up in the incorrect window.
2466 NotifyMotionArgs downMotionArgs =
2467 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2468 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2469 mDispatcher->notifyMotion(&downMotionArgs);
2470
2471 firstWindow->consumeMotionDown();
2472 secondWindow->assertNoEvents();
2473}
2474
2475// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2476// the event should be treated as being in the logical display space.
2477TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2478 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2479 // Send down to the first window. The point is represented in the logical display space. The
2480 // point is selected so that if the hit test was done in logical display space, then it would
2481 // end up in the incorrect window.
2482 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2483 PointF{75 * 2, 55 * 4});
2484
2485 firstWindow->consumeMotionDown();
2486 secondWindow->assertNoEvents();
2487}
2488
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002489// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2490// event should be treated as being in the logical display space.
2491TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2492 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2493
2494 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2495 ui::Transform injectedEventTransform;
2496 injectedEventTransform.set(matrix);
2497 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2498 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2499
2500 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2501 .displayId(ADISPLAY_ID_DEFAULT)
2502 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2503 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2504 .x(untransformedPoint.x)
2505 .y(untransformedPoint.y))
2506 .build();
2507 event.transform(matrix);
2508
2509 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2510 InputEventInjectionSync::WAIT_FOR_RESULT);
2511
2512 firstWindow->consumeMotionDown();
2513 secondWindow->assertNoEvents();
2514}
2515
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002516TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2517 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2518
2519 // Send down to the second window.
2520 NotifyMotionArgs downMotionArgs =
2521 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2522 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2523 mDispatcher->notifyMotion(&downMotionArgs);
2524
2525 firstWindow->assertNoEvents();
2526 const MotionEvent* event = secondWindow->consumeMotion();
2527 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2528
2529 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2530 EXPECT_EQ(300, event->getRawX(0));
2531 EXPECT_EQ(880, event->getRawY(0));
2532
2533 // Ensure that the x and y values are in the window's coordinate space.
2534 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2535 // the logical display space. This will be the origin of the window space.
2536 EXPECT_EQ(100, event->getX(0));
2537 EXPECT_EQ(80, event->getY(0));
2538}
2539
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002540using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2541 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002542
2543class TransferTouchFixture : public InputDispatcherTest,
2544 public ::testing::WithParamInterface<TransferFunction> {};
2545
2546TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002548
2549 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002550 sp<FakeWindowHandle> firstWindow =
2551 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2552 sp<FakeWindowHandle> secondWindow =
2553 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002554
2555 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002557
2558 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002559 NotifyMotionArgs downMotionArgs =
2560 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2561 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002562 mDispatcher->notifyMotion(&downMotionArgs);
2563 // Only the first window should get the down event
2564 firstWindow->consumeMotionDown();
2565 secondWindow->assertNoEvents();
2566
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002567 // Transfer touch to the second window
2568 TransferFunction f = GetParam();
2569 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2570 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002571 // The first window gets cancel and the second gets down
2572 firstWindow->consumeMotionCancel();
2573 secondWindow->consumeMotionDown();
2574
2575 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002576 NotifyMotionArgs upMotionArgs =
2577 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2578 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002579 mDispatcher->notifyMotion(&upMotionArgs);
2580 // The first window gets no events and the second gets up
2581 firstWindow->assertNoEvents();
2582 secondWindow->consumeMotionUp();
2583}
2584
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002585/**
2586 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2587 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2588 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2589 * natural to the user.
2590 * In this test, we are sending a pointer to both spy window and first window. We then try to
2591 * transfer touch to the second window. The dispatcher should identify the first window as the
2592 * one that should lose the gesture, and therefore the action should be to move the gesture from
2593 * the first window to the second.
2594 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2595 * the other API, as well.
2596 */
2597TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2598 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2599
2600 // Create a couple of windows + a spy window
2601 sp<FakeWindowHandle> spyWindow =
2602 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2603 spyWindow->setTrustedOverlay(true);
2604 spyWindow->setSpy(true);
2605 sp<FakeWindowHandle> firstWindow =
2606 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2607 sp<FakeWindowHandle> secondWindow =
2608 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2609
2610 // Add the windows to the dispatcher
2611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2612
2613 // Send down to the first window
2614 NotifyMotionArgs downMotionArgs =
2615 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2616 ADISPLAY_ID_DEFAULT);
2617 mDispatcher->notifyMotion(&downMotionArgs);
2618 // Only the first window and spy should get the down event
2619 spyWindow->consumeMotionDown();
2620 firstWindow->consumeMotionDown();
2621
2622 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2623 // if f === 'transferTouch'.
2624 TransferFunction f = GetParam();
2625 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2626 ASSERT_TRUE(success);
2627 // The first window gets cancel and the second gets down
2628 firstWindow->consumeMotionCancel();
2629 secondWindow->consumeMotionDown();
2630
2631 // Send up event to the second window
2632 NotifyMotionArgs upMotionArgs =
2633 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2634 ADISPLAY_ID_DEFAULT);
2635 mDispatcher->notifyMotion(&upMotionArgs);
2636 // The first window gets no events and the second+spy get up
2637 firstWindow->assertNoEvents();
2638 spyWindow->consumeMotionUp();
2639 secondWindow->consumeMotionUp();
2640}
2641
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002642TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002644
2645 PointF touchPoint = {10, 10};
2646
2647 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002648 sp<FakeWindowHandle> firstWindow =
2649 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002650 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002651 sp<FakeWindowHandle> secondWindow =
2652 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002653 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002654
2655 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002657
2658 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002659 NotifyMotionArgs downMotionArgs =
2660 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2661 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002662 mDispatcher->notifyMotion(&downMotionArgs);
2663 // Only the first window should get the down event
2664 firstWindow->consumeMotionDown();
2665 secondWindow->assertNoEvents();
2666
2667 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002668 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002669 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002670 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002671 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2672 // Only the first window should get the pointer down event
2673 firstWindow->consumeMotionPointerDown(1);
2674 secondWindow->assertNoEvents();
2675
2676 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002677 TransferFunction f = GetParam();
2678 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2679 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002680 // The first window gets cancel and the second gets down and pointer down
2681 firstWindow->consumeMotionCancel();
2682 secondWindow->consumeMotionDown();
2683 secondWindow->consumeMotionPointerDown(1);
2684
2685 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002686 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002687 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002688 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002689 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2690 // The first window gets nothing and the second gets pointer up
2691 firstWindow->assertNoEvents();
2692 secondWindow->consumeMotionPointerUp(1);
2693
2694 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002695 NotifyMotionArgs upMotionArgs =
2696 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2697 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002698 mDispatcher->notifyMotion(&upMotionArgs);
2699 // The first window gets nothing and the second gets up
2700 firstWindow->assertNoEvents();
2701 secondWindow->consumeMotionUp();
2702}
2703
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002704// For the cases of single pointer touch and two pointers non-split touch, the api's
2705// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2706// for the case where there are multiple pointers split across several windows.
2707INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2708 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002709 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2710 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002711 return dispatcher->transferTouch(destChannelToken,
2712 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002713 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002714 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2715 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002716 return dispatcher->transferTouchFocus(from, to,
2717 false /*isDragAndDrop*/);
2718 }));
2719
Svet Ganov5d3bc372020-01-26 23:11:07 -08002720TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002721 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002722
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002723 sp<FakeWindowHandle> firstWindow =
2724 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002725 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002726
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002727 sp<FakeWindowHandle> secondWindow =
2728 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002729 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002730
2731 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002733
2734 PointF pointInFirst = {300, 200};
2735 PointF pointInSecond = {300, 600};
2736
2737 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002738 NotifyMotionArgs firstDownMotionArgs =
2739 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2740 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002741 mDispatcher->notifyMotion(&firstDownMotionArgs);
2742 // Only the first window should get the down event
2743 firstWindow->consumeMotionDown();
2744 secondWindow->assertNoEvents();
2745
2746 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002747 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002748 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002749 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002750 mDispatcher->notifyMotion(&secondDownMotionArgs);
2751 // The first window gets a move and the second a down
2752 firstWindow->consumeMotionMove();
2753 secondWindow->consumeMotionDown();
2754
2755 // Transfer touch focus to the second window
2756 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2757 // The first window gets cancel and the new gets pointer down (it already saw down)
2758 firstWindow->consumeMotionCancel();
2759 secondWindow->consumeMotionPointerDown(1);
2760
2761 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002762 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002763 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002764 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002765 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2766 // The first window gets nothing and the second gets pointer up
2767 firstWindow->assertNoEvents();
2768 secondWindow->consumeMotionPointerUp(1);
2769
2770 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002771 NotifyMotionArgs upMotionArgs =
2772 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2773 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002774 mDispatcher->notifyMotion(&upMotionArgs);
2775 // The first window gets nothing and the second gets up
2776 firstWindow->assertNoEvents();
2777 secondWindow->consumeMotionUp();
2778}
2779
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002780// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2781// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2782// touch is not supported, so the touch should continue on those windows and the transferred-to
2783// window should get nothing.
2784TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2785 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2786
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002787 sp<FakeWindowHandle> firstWindow =
2788 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2789 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002790
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002791 sp<FakeWindowHandle> secondWindow =
2792 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2793 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002794
2795 // Add the windows to the dispatcher
2796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2797
2798 PointF pointInFirst = {300, 200};
2799 PointF pointInSecond = {300, 600};
2800
2801 // Send down to the first window
2802 NotifyMotionArgs firstDownMotionArgs =
2803 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2804 ADISPLAY_ID_DEFAULT, {pointInFirst});
2805 mDispatcher->notifyMotion(&firstDownMotionArgs);
2806 // Only the first window should get the down event
2807 firstWindow->consumeMotionDown();
2808 secondWindow->assertNoEvents();
2809
2810 // Send down to the second window
2811 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002812 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002813 {pointInFirst, pointInSecond});
2814 mDispatcher->notifyMotion(&secondDownMotionArgs);
2815 // The first window gets a move and the second a down
2816 firstWindow->consumeMotionMove();
2817 secondWindow->consumeMotionDown();
2818
2819 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002820 const bool transferred =
2821 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002822 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2823 ASSERT_FALSE(transferred);
2824 firstWindow->assertNoEvents();
2825 secondWindow->assertNoEvents();
2826
2827 // The rest of the dispatch should proceed as normal
2828 // Send pointer up to the second window
2829 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002830 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002831 {pointInFirst, pointInSecond});
2832 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2833 // The first window gets MOVE and the second gets pointer up
2834 firstWindow->consumeMotionMove();
2835 secondWindow->consumeMotionUp();
2836
2837 // Send up event to the first window
2838 NotifyMotionArgs upMotionArgs =
2839 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2840 ADISPLAY_ID_DEFAULT);
2841 mDispatcher->notifyMotion(&upMotionArgs);
2842 // The first window gets nothing and the second gets up
2843 firstWindow->consumeMotionUp();
2844 secondWindow->assertNoEvents();
2845}
2846
Arthur Hungabbb9d82021-09-01 14:52:30 +00002847// This case will create two windows and one mirrored window on the default display and mirror
2848// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2849// the windows info of second display before default display.
2850TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2851 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2852 sp<FakeWindowHandle> firstWindowInPrimary =
2853 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2854 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002855 sp<FakeWindowHandle> secondWindowInPrimary =
2856 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2857 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002858
2859 sp<FakeWindowHandle> mirrorWindowInPrimary =
2860 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2861 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002862
2863 sp<FakeWindowHandle> firstWindowInSecondary =
2864 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2865 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002866
2867 sp<FakeWindowHandle> secondWindowInSecondary =
2868 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2869 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002870
2871 // Update window info, let it find window handle of second display first.
2872 mDispatcher->setInputWindows(
2873 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2874 {ADISPLAY_ID_DEFAULT,
2875 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2876
2877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2878 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2879 {50, 50}))
2880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2881
2882 // Window should receive motion event.
2883 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2884
2885 // Transfer touch focus
2886 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2887 secondWindowInPrimary->getToken()));
2888 // The first window gets cancel.
2889 firstWindowInPrimary->consumeMotionCancel();
2890 secondWindowInPrimary->consumeMotionDown();
2891
2892 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2893 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2894 ADISPLAY_ID_DEFAULT, {150, 50}))
2895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2896 firstWindowInPrimary->assertNoEvents();
2897 secondWindowInPrimary->consumeMotionMove();
2898
2899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2900 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2901 {150, 50}))
2902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2903 firstWindowInPrimary->assertNoEvents();
2904 secondWindowInPrimary->consumeMotionUp();
2905}
2906
2907// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2908// 'transferTouch' api.
2909TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2910 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2911 sp<FakeWindowHandle> firstWindowInPrimary =
2912 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2913 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002914 sp<FakeWindowHandle> secondWindowInPrimary =
2915 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2916 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002917
2918 sp<FakeWindowHandle> mirrorWindowInPrimary =
2919 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2920 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002921
2922 sp<FakeWindowHandle> firstWindowInSecondary =
2923 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2924 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002925
2926 sp<FakeWindowHandle> secondWindowInSecondary =
2927 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2928 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002929
2930 // Update window info, let it find window handle of second display first.
2931 mDispatcher->setInputWindows(
2932 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2933 {ADISPLAY_ID_DEFAULT,
2934 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2935
2936 // Touch on second display.
2937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2938 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2939 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2940
2941 // Window should receive motion event.
2942 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2943
2944 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002945 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002946
2947 // The first window gets cancel.
2948 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2949 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2950
2951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2952 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2953 SECOND_DISPLAY_ID, {150, 50}))
2954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2955 firstWindowInPrimary->assertNoEvents();
2956 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2957
2958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2959 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2960 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2961 firstWindowInPrimary->assertNoEvents();
2962 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2963}
2964
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002965TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002967 sp<FakeWindowHandle> window =
2968 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2969
Vishnu Nair47074b82020-08-14 11:54:47 -07002970 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002972 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002973
2974 window->consumeFocusEvent(true);
2975
2976 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2977 mDispatcher->notifyKey(&keyArgs);
2978
2979 // Window should receive key down event.
2980 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2981}
2982
2983TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002985 sp<FakeWindowHandle> window =
2986 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2987
Arthur Hung72d8dc32020-03-28 00:48:39 +00002988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002989
2990 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2991 mDispatcher->notifyKey(&keyArgs);
2992 mDispatcher->waitForIdle();
2993
2994 window->assertNoEvents();
2995}
2996
2997// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2998TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002999 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003000 sp<FakeWindowHandle> window =
3001 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3002
Arthur Hung72d8dc32020-03-28 00:48:39 +00003003 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003004
3005 // Send key
3006 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3007 mDispatcher->notifyKey(&keyArgs);
3008 // Send motion
3009 NotifyMotionArgs motionArgs =
3010 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3011 ADISPLAY_ID_DEFAULT);
3012 mDispatcher->notifyMotion(&motionArgs);
3013
3014 // Window should receive only the motion event
3015 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3016 window->assertNoEvents(); // Key event or focus event will not be received
3017}
3018
arthurhungea3f4fc2020-12-21 23:18:53 +08003019TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3020 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3021
arthurhungea3f4fc2020-12-21 23:18:53 +08003022 sp<FakeWindowHandle> firstWindow =
3023 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
3024 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003025
arthurhungea3f4fc2020-12-21 23:18:53 +08003026 sp<FakeWindowHandle> secondWindow =
3027 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
3028 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003029
3030 // Add the windows to the dispatcher
3031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3032
3033 PointF pointInFirst = {300, 200};
3034 PointF pointInSecond = {300, 600};
3035
3036 // Send down to the first window
3037 NotifyMotionArgs firstDownMotionArgs =
3038 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3039 ADISPLAY_ID_DEFAULT, {pointInFirst});
3040 mDispatcher->notifyMotion(&firstDownMotionArgs);
3041 // Only the first window should get the down event
3042 firstWindow->consumeMotionDown();
3043 secondWindow->assertNoEvents();
3044
3045 // Send down to the second window
3046 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003047 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003048 {pointInFirst, pointInSecond});
3049 mDispatcher->notifyMotion(&secondDownMotionArgs);
3050 // The first window gets a move and the second a down
3051 firstWindow->consumeMotionMove();
3052 secondWindow->consumeMotionDown();
3053
3054 // Send pointer cancel to the second window
3055 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003056 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003057 {pointInFirst, pointInSecond});
3058 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3059 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3060 // The first window gets move and the second gets cancel.
3061 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3062 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3063
3064 // Send up event.
3065 NotifyMotionArgs upMotionArgs =
3066 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3067 ADISPLAY_ID_DEFAULT);
3068 mDispatcher->notifyMotion(&upMotionArgs);
3069 // The first window gets up and the second gets nothing.
3070 firstWindow->consumeMotionUp();
3071 secondWindow->assertNoEvents();
3072}
3073
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003074TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3075 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3076
3077 sp<FakeWindowHandle> window =
3078 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3080 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3081 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3082 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3083
3084 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3085 window->assertNoEvents();
3086 mDispatcher->waitForIdle();
3087}
3088
chaviwd1c23182019-12-20 18:44:56 -08003089class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003090public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003091 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003092 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003093 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003094 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003095 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003096 }
3097
chaviwd1c23182019-12-20 18:44:56 -08003098 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3099
3100 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3101 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3102 expectedDisplayId, expectedFlags);
3103 }
3104
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003105 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3106
3107 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3108
chaviwd1c23182019-12-20 18:44:56 -08003109 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3110 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3111 expectedDisplayId, expectedFlags);
3112 }
3113
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003114 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3115 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3116 expectedDisplayId, expectedFlags);
3117 }
3118
chaviwd1c23182019-12-20 18:44:56 -08003119 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3120 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3121 expectedDisplayId, expectedFlags);
3122 }
3123
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003124 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3125 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3126 expectedDisplayId, expectedFlags);
3127 }
3128
Arthur Hungfbfa5722021-11-16 02:45:54 +00003129 void consumeMotionPointerDown(int32_t pointerIdx) {
3130 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3131 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3132 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3133 0 /*expectedFlags*/);
3134 }
3135
Evan Rosky84f07f02021-04-16 10:42:42 -07003136 MotionEvent* consumeMotion() {
3137 InputEvent* event = mInputReceiver->consume();
3138 if (!event) {
3139 ADD_FAILURE() << "No event was produced";
3140 return nullptr;
3141 }
3142 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3143 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3144 return nullptr;
3145 }
3146 return static_cast<MotionEvent*>(event);
3147 }
3148
chaviwd1c23182019-12-20 18:44:56 -08003149 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3150
3151private:
3152 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003153};
3154
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003155using InputDispatcherMonitorTest = InputDispatcherTest;
3156
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003157/**
3158 * Two entities that receive touch: A window, and a global monitor.
3159 * The touch goes to the window, and then the window disappears.
3160 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3161 * for the monitor, as well.
3162 * 1. foregroundWindow
3163 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3164 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003165TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003166 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3167 sp<FakeWindowHandle> window =
3168 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3169
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003170 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003171
3172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3175 {100, 200}))
3176 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3177
3178 // Both the foreground window and the global monitor should receive the touch down
3179 window->consumeMotionDown();
3180 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3181
3182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3183 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3184 ADISPLAY_ID_DEFAULT, {110, 200}))
3185 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3186
3187 window->consumeMotionMove();
3188 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3189
3190 // Now the foreground window goes away
3191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3192 window->consumeMotionCancel();
3193 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3194
3195 // If more events come in, there will be no more foreground window to send them to. This will
3196 // cause a cancel for the monitor, as well.
3197 ASSERT_EQ(InputEventInjectionResult::FAILED,
3198 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3199 ADISPLAY_ID_DEFAULT, {120, 200}))
3200 << "Injection should fail because the window was removed";
3201 window->assertNoEvents();
3202 // Global monitor now gets the cancel
3203 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3204}
3205
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003206TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003207 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003208 sp<FakeWindowHandle> window =
3209 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003211
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003212 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003213
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003215 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003216 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003217 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003218 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003219}
3220
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003221TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3222 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003223
Chris Yea209fde2020-07-22 13:54:51 -07003224 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003225 sp<FakeWindowHandle> window =
3226 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003228
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003230 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003231 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003232 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003233 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003234
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003235 // Pilfer pointers from the monitor.
3236 // This should not do anything and the window should continue to receive events.
3237 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003240 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3241 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003242 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003243
3244 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3245 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003246}
3247
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003248TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003249 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3250 sp<FakeWindowHandle> window =
3251 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3253 window->setWindowOffset(20, 40);
3254 window->setWindowTransform(0, 1, -1, 0);
3255
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003256 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003257
3258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3259 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3260 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3261 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3262 MotionEvent* event = monitor.consumeMotion();
3263 // Even though window has transform, gesture monitor must not.
3264 ASSERT_EQ(ui::Transform(), event->getTransform());
3265}
3266
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003267TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003268 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003269 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003270
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003271 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003272 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003273 << "Injection should fail if there is a monitor, but no touchable window";
3274 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003275}
3276
chaviw81e2bb92019-12-18 15:03:51 -08003277TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003278 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003279 sp<FakeWindowHandle> window =
3280 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3281
Arthur Hung72d8dc32020-03-28 00:48:39 +00003282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003283
3284 NotifyMotionArgs motionArgs =
3285 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3286 ADISPLAY_ID_DEFAULT);
3287
3288 mDispatcher->notifyMotion(&motionArgs);
3289 // Window should receive motion down event.
3290 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3291
3292 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003293 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003294 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3295 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3296 motionArgs.pointerCoords[0].getX() - 10);
3297
3298 mDispatcher->notifyMotion(&motionArgs);
3299 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3300 0 /*expectedFlags*/);
3301}
3302
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003303/**
3304 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3305 * the device default right away. In the test scenario, we check both the default value,
3306 * and the action of enabling / disabling.
3307 */
3308TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003310 sp<FakeWindowHandle> window =
3311 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003312 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003313
3314 // Set focused application.
3315 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003316 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003317
3318 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003320 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003321 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3322
3323 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003324 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003326 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3327
3328 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003329 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003330 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003331 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003332 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003334 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003335 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3336
3337 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003338 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3341
3342 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003343 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003344 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003345 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003346 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003348 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003349 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3350
3351 window->assertNoEvents();
3352}
3353
Gang Wange9087892020-01-07 12:17:14 -05003354TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003355 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003356 sp<FakeWindowHandle> window =
3357 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3358
3359 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003360 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003361
Arthur Hung72d8dc32020-03-28 00:48:39 +00003362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003363 setFocusedWindow(window);
3364
Gang Wange9087892020-01-07 12:17:14 -05003365 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3366
3367 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3368 mDispatcher->notifyKey(&keyArgs);
3369
3370 InputEvent* event = window->consume();
3371 ASSERT_NE(event, nullptr);
3372
3373 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3374 ASSERT_NE(verified, nullptr);
3375 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3376
3377 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3378 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3379 ASSERT_EQ(keyArgs.source, verified->source);
3380 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3381
3382 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3383
3384 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003385 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003386 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003387 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3388 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3389 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3390 ASSERT_EQ(0, verifiedKey.repeatCount);
3391}
3392
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003393TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003394 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003395 sp<FakeWindowHandle> window =
3396 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3397
3398 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3399
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003400 ui::Transform transform;
3401 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3402
3403 gui::DisplayInfo displayInfo;
3404 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3405 displayInfo.transform = transform;
3406
3407 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003408
3409 NotifyMotionArgs motionArgs =
3410 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3411 ADISPLAY_ID_DEFAULT);
3412 mDispatcher->notifyMotion(&motionArgs);
3413
3414 InputEvent* event = window->consume();
3415 ASSERT_NE(event, nullptr);
3416
3417 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3418 ASSERT_NE(verified, nullptr);
3419 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3420
3421 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3422 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3423 EXPECT_EQ(motionArgs.source, verified->source);
3424 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3425
3426 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3427
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003428 const vec2 rawXY =
3429 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3430 motionArgs.pointerCoords[0].getXYValue());
3431 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3432 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003433 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003434 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003435 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003436 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3437 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3438}
3439
chaviw09c8d2d2020-08-24 15:48:26 -07003440/**
3441 * Ensure that separate calls to sign the same data are generating the same key.
3442 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3443 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3444 * tests.
3445 */
3446TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3447 KeyEvent event = getTestKeyEvent();
3448 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3449
3450 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3451 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3452 ASSERT_EQ(hmac1, hmac2);
3453}
3454
3455/**
3456 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3457 */
3458TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3459 KeyEvent event = getTestKeyEvent();
3460 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3461 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3462
3463 verifiedEvent.deviceId += 1;
3464 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3465
3466 verifiedEvent.source += 1;
3467 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3468
3469 verifiedEvent.eventTimeNanos += 1;
3470 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3471
3472 verifiedEvent.displayId += 1;
3473 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3474
3475 verifiedEvent.action += 1;
3476 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3477
3478 verifiedEvent.downTimeNanos += 1;
3479 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3480
3481 verifiedEvent.flags += 1;
3482 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3483
3484 verifiedEvent.keyCode += 1;
3485 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3486
3487 verifiedEvent.scanCode += 1;
3488 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3489
3490 verifiedEvent.metaState += 1;
3491 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3492
3493 verifiedEvent.repeatCount += 1;
3494 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3495}
3496
Vishnu Nair958da932020-08-21 17:12:37 -07003497TEST_F(InputDispatcherTest, SetFocusedWindow) {
3498 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3499 sp<FakeWindowHandle> windowTop =
3500 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3501 sp<FakeWindowHandle> windowSecond =
3502 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3503 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3504
3505 // Top window is also focusable but is not granted focus.
3506 windowTop->setFocusable(true);
3507 windowSecond->setFocusable(true);
3508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3509 setFocusedWindow(windowSecond);
3510
3511 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3513 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003514
3515 // Focused window should receive event.
3516 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3517 windowTop->assertNoEvents();
3518}
3519
3520TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3521 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3522 sp<FakeWindowHandle> window =
3523 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3524 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3525
3526 window->setFocusable(true);
3527 // Release channel for window is no longer valid.
3528 window->releaseChannel();
3529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3530 setFocusedWindow(window);
3531
3532 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003533 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3534 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003535
3536 // window channel is invalid, so it should not receive any input event.
3537 window->assertNoEvents();
3538}
3539
3540TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3541 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3542 sp<FakeWindowHandle> window =
3543 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003544 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003545 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3546
Vishnu Nair958da932020-08-21 17:12:37 -07003547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3548 setFocusedWindow(window);
3549
3550 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003551 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3552 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003553
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003554 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003555 window->assertNoEvents();
3556}
3557
3558TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3559 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3560 sp<FakeWindowHandle> windowTop =
3561 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3562 sp<FakeWindowHandle> windowSecond =
3563 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3564 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3565
3566 windowTop->setFocusable(true);
3567 windowSecond->setFocusable(true);
3568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3569 setFocusedWindow(windowTop);
3570 windowTop->consumeFocusEvent(true);
3571
3572 setFocusedWindow(windowSecond, windowTop);
3573 windowSecond->consumeFocusEvent(true);
3574 windowTop->consumeFocusEvent(false);
3575
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3577 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003578
3579 // Focused window should receive event.
3580 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3581}
3582
3583TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3584 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3585 sp<FakeWindowHandle> windowTop =
3586 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3587 sp<FakeWindowHandle> windowSecond =
3588 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3589 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3590
3591 windowTop->setFocusable(true);
3592 windowSecond->setFocusable(true);
3593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3594 setFocusedWindow(windowSecond, windowTop);
3595
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003596 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3597 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003598
3599 // Event should be dropped.
3600 windowTop->assertNoEvents();
3601 windowSecond->assertNoEvents();
3602}
3603
3604TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3606 sp<FakeWindowHandle> window =
3607 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3608 sp<FakeWindowHandle> previousFocusedWindow =
3609 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3610 ADISPLAY_ID_DEFAULT);
3611 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3612
3613 window->setFocusable(true);
3614 previousFocusedWindow->setFocusable(true);
3615 window->setVisible(false);
3616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3617 setFocusedWindow(previousFocusedWindow);
3618 previousFocusedWindow->consumeFocusEvent(true);
3619
3620 // Requesting focus on invisible window takes focus from currently focused window.
3621 setFocusedWindow(window);
3622 previousFocusedWindow->consumeFocusEvent(false);
3623
3624 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003626 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003627 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003628
3629 // Window does not get focus event or key down.
3630 window->assertNoEvents();
3631
3632 // Window becomes visible.
3633 window->setVisible(true);
3634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3635
3636 // Window receives focus event.
3637 window->consumeFocusEvent(true);
3638 // Focused window receives key down.
3639 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3640}
3641
Vishnu Nair599f1412021-06-21 10:39:58 -07003642TEST_F(InputDispatcherTest, DisplayRemoved) {
3643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3644 sp<FakeWindowHandle> window =
3645 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3646 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3647
3648 // window is granted focus.
3649 window->setFocusable(true);
3650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3651 setFocusedWindow(window);
3652 window->consumeFocusEvent(true);
3653
3654 // When a display is removed window loses focus.
3655 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3656 window->consumeFocusEvent(false);
3657}
3658
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003659/**
3660 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3661 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3662 * of the 'slipperyEnterWindow'.
3663 *
3664 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3665 * a way so that the touched location is no longer covered by the top window.
3666 *
3667 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3668 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3669 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3670 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3671 * with ACTION_DOWN).
3672 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3673 * window moved itself away from the touched location and had Flag::SLIPPERY.
3674 *
3675 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3676 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3677 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3678 *
3679 * In this test, we ensure that the event received by the bottom window has
3680 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3681 */
3682TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003683 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3684 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003685
3686 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3687 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3688
3689 sp<FakeWindowHandle> slipperyExitWindow =
3690 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003691 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003692 // Make sure this one overlaps the bottom window
3693 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3694 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3695 // one. Windows with the same owner are not considered to be occluding each other.
3696 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3697
3698 sp<FakeWindowHandle> slipperyEnterWindow =
3699 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3700 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3701
3702 mDispatcher->setInputWindows(
3703 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3704
3705 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3706 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3707 ADISPLAY_ID_DEFAULT, {{50, 50}});
3708 mDispatcher->notifyMotion(&args);
3709 slipperyExitWindow->consumeMotionDown();
3710 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3711 mDispatcher->setInputWindows(
3712 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3713
3714 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3715 ADISPLAY_ID_DEFAULT, {{51, 51}});
3716 mDispatcher->notifyMotion(&args);
3717
3718 slipperyExitWindow->consumeMotionCancel();
3719
3720 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3721 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3722}
3723
Garfield Tan1c7bc862020-01-28 13:24:04 -08003724class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3725protected:
3726 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3727 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3728
Chris Yea209fde2020-07-22 13:54:51 -07003729 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003730 sp<FakeWindowHandle> mWindow;
3731
3732 virtual void SetUp() override {
3733 mFakePolicy = new FakeInputDispatcherPolicy();
3734 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003735 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003736 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3737 ASSERT_EQ(OK, mDispatcher->start());
3738
3739 setUpWindow();
3740 }
3741
3742 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003743 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003744 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3745
Vishnu Nair47074b82020-08-14 11:54:47 -07003746 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003748 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003749 mWindow->consumeFocusEvent(true);
3750 }
3751
Chris Ye2ad95392020-09-01 13:44:44 -07003752 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003753 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003754 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003755 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3756 mDispatcher->notifyKey(&keyArgs);
3757
3758 // Window should receive key down event.
3759 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3760 }
3761
3762 void expectKeyRepeatOnce(int32_t repeatCount) {
3763 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3764 InputEvent* repeatEvent = mWindow->consume();
3765 ASSERT_NE(nullptr, repeatEvent);
3766
3767 uint32_t eventType = repeatEvent->getType();
3768 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3769
3770 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3771 uint32_t eventAction = repeatKeyEvent->getAction();
3772 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3773 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3774 }
3775
Chris Ye2ad95392020-09-01 13:44:44 -07003776 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003777 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003778 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003779 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3780 mDispatcher->notifyKey(&keyArgs);
3781
3782 // Window should receive key down event.
3783 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3784 0 /*expectedFlags*/);
3785 }
3786};
3787
3788TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003789 sendAndConsumeKeyDown(1 /* deviceId */);
3790 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3791 expectKeyRepeatOnce(repeatCount);
3792 }
3793}
3794
3795TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3796 sendAndConsumeKeyDown(1 /* deviceId */);
3797 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3798 expectKeyRepeatOnce(repeatCount);
3799 }
3800 sendAndConsumeKeyDown(2 /* deviceId */);
3801 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003802 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3803 expectKeyRepeatOnce(repeatCount);
3804 }
3805}
3806
3807TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003808 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003809 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003810 sendAndConsumeKeyUp(1 /* deviceId */);
3811 mWindow->assertNoEvents();
3812}
3813
3814TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3815 sendAndConsumeKeyDown(1 /* deviceId */);
3816 expectKeyRepeatOnce(1 /*repeatCount*/);
3817 sendAndConsumeKeyDown(2 /* deviceId */);
3818 expectKeyRepeatOnce(1 /*repeatCount*/);
3819 // Stale key up from device 1.
3820 sendAndConsumeKeyUp(1 /* deviceId */);
3821 // Device 2 is still down, keep repeating
3822 expectKeyRepeatOnce(2 /*repeatCount*/);
3823 expectKeyRepeatOnce(3 /*repeatCount*/);
3824 // Device 2 key up
3825 sendAndConsumeKeyUp(2 /* deviceId */);
3826 mWindow->assertNoEvents();
3827}
3828
3829TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3830 sendAndConsumeKeyDown(1 /* deviceId */);
3831 expectKeyRepeatOnce(1 /*repeatCount*/);
3832 sendAndConsumeKeyDown(2 /* deviceId */);
3833 expectKeyRepeatOnce(1 /*repeatCount*/);
3834 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3835 sendAndConsumeKeyUp(2 /* deviceId */);
3836 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003837 mWindow->assertNoEvents();
3838}
3839
liushenxiang42232912021-05-21 20:24:09 +08003840TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3841 sendAndConsumeKeyDown(DEVICE_ID);
3842 expectKeyRepeatOnce(1 /*repeatCount*/);
3843 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3844 mDispatcher->notifyDeviceReset(&args);
3845 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3846 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3847 mWindow->assertNoEvents();
3848}
3849
Garfield Tan1c7bc862020-01-28 13:24:04 -08003850TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003851 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003852 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3853 InputEvent* repeatEvent = mWindow->consume();
3854 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3855 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3856 IdGenerator::getSource(repeatEvent->getId()));
3857 }
3858}
3859
3860TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003861 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003862
3863 std::unordered_set<int32_t> idSet;
3864 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3865 InputEvent* repeatEvent = mWindow->consume();
3866 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3867 int32_t id = repeatEvent->getId();
3868 EXPECT_EQ(idSet.end(), idSet.find(id));
3869 idSet.insert(id);
3870 }
3871}
3872
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003873/* Test InputDispatcher for MultiDisplay */
3874class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3875public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003876 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003877 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003878
Chris Yea209fde2020-07-22 13:54:51 -07003879 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003880 windowInPrimary =
3881 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003882
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003883 // Set focus window for primary display, but focused display would be second one.
3884 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003885 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003887 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003888 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003889
Chris Yea209fde2020-07-22 13:54:51 -07003890 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003891 windowInSecondary =
3892 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003893 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003894 // Set focus display to second one.
3895 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3896 // Set focus window for second display.
3897 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003898 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003899 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003900 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003901 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003902 }
3903
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003904 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003905 InputDispatcherTest::TearDown();
3906
Chris Yea209fde2020-07-22 13:54:51 -07003907 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003908 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003909 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003910 windowInSecondary.clear();
3911 }
3912
3913protected:
Chris Yea209fde2020-07-22 13:54:51 -07003914 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003915 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003916 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003917 sp<FakeWindowHandle> windowInSecondary;
3918};
3919
3920TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3921 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3924 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003925 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003926 windowInSecondary->assertNoEvents();
3927
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003928 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3930 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003932 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003933 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003934}
3935
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003936TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003937 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3939 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003940 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003941 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003942 windowInSecondary->assertNoEvents();
3943
3944 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003946 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003947 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003948 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003949
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003950 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003951 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003954 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3955 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003956
3957 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003958 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003959 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003960 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003961 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003962 windowInSecondary->assertNoEvents();
3963}
3964
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003965// Test per-display input monitors for motion event.
3966TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003967 FakeMonitorReceiver monitorInPrimary =
3968 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3969 FakeMonitorReceiver monitorInSecondary =
3970 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003971
3972 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3974 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3975 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003976 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003977 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003978 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003979 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003980
3981 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003985 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003986 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003987 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003988 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003989
3990 // Test inject a non-pointer motion event.
3991 // If specific a display, it will dispatch to the focused window of particular display,
3992 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3994 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3995 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003996 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003997 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003998 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003999 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004000}
4001
4002// Test per-display input monitors for key event.
4003TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004004 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004005 FakeMonitorReceiver monitorInPrimary =
4006 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4007 FakeMonitorReceiver monitorInSecondary =
4008 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004009
4010 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4012 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004013 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004014 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004015 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004016 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004017}
4018
Vishnu Nair958da932020-08-21 17:12:37 -07004019TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4020 sp<FakeWindowHandle> secondWindowInPrimary =
4021 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
4022 secondWindowInPrimary->setFocusable(true);
4023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4024 setFocusedWindow(secondWindowInPrimary);
4025 windowInPrimary->consumeFocusEvent(false);
4026 secondWindowInPrimary->consumeFocusEvent(true);
4027
4028 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4030 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004031 windowInPrimary->assertNoEvents();
4032 windowInSecondary->assertNoEvents();
4033 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4034}
4035
Arthur Hungdfd528e2021-12-08 13:23:04 +00004036TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4037 FakeMonitorReceiver monitorInPrimary =
4038 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4039 FakeMonitorReceiver monitorInSecondary =
4040 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4041
4042 // Test touch down on primary display.
4043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4044 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4045 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4046 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4047 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4048
4049 // Test touch down on second display.
4050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4051 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4053 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4054 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4055
4056 // Trigger cancel touch.
4057 mDispatcher->cancelCurrentTouch();
4058 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4059 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4060 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4061 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4062
4063 // Test inject a move motion event, no window/monitor should receive the event.
4064 ASSERT_EQ(InputEventInjectionResult::FAILED,
4065 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4066 ADISPLAY_ID_DEFAULT, {110, 200}))
4067 << "Inject motion event should return InputEventInjectionResult::FAILED";
4068 windowInPrimary->assertNoEvents();
4069 monitorInPrimary.assertNoEvents();
4070
4071 ASSERT_EQ(InputEventInjectionResult::FAILED,
4072 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4073 SECOND_DISPLAY_ID, {110, 200}))
4074 << "Inject motion event should return InputEventInjectionResult::FAILED";
4075 windowInSecondary->assertNoEvents();
4076 monitorInSecondary.assertNoEvents();
4077}
4078
Jackal Guof9696682018-10-05 12:23:23 +08004079class InputFilterTest : public InputDispatcherTest {
4080protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004081 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4082 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004083 NotifyMotionArgs motionArgs;
4084
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004085 motionArgs =
4086 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004087 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004088 motionArgs =
4089 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004090 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004091 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004092 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004093 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4094 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004095 } else {
4096 mFakePolicy->assertFilterInputEventWasNotCalled();
4097 }
4098 }
4099
4100 void testNotifyKey(bool expectToBeFiltered) {
4101 NotifyKeyArgs keyArgs;
4102
4103 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4104 mDispatcher->notifyKey(&keyArgs);
4105 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4106 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004107 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004108
4109 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004110 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004111 } else {
4112 mFakePolicy->assertFilterInputEventWasNotCalled();
4113 }
4114 }
4115};
4116
4117// Test InputFilter for MotionEvent
4118TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4119 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4120 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4121 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4122
4123 // Enable InputFilter
4124 mDispatcher->setInputFilterEnabled(true);
4125 // Test touch on both primary and second display, and check if both events are filtered.
4126 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4127 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4128
4129 // Disable InputFilter
4130 mDispatcher->setInputFilterEnabled(false);
4131 // Test touch on both primary and second display, and check if both events aren't filtered.
4132 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4133 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4134}
4135
4136// Test InputFilter for KeyEvent
4137TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4138 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4139 testNotifyKey(/*expectToBeFiltered*/ false);
4140
4141 // Enable InputFilter
4142 mDispatcher->setInputFilterEnabled(true);
4143 // Send a key event, and check if it is filtered.
4144 testNotifyKey(/*expectToBeFiltered*/ true);
4145
4146 // Disable InputFilter
4147 mDispatcher->setInputFilterEnabled(false);
4148 // Send a key event, and check if it isn't filtered.
4149 testNotifyKey(/*expectToBeFiltered*/ false);
4150}
4151
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004152// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4153// logical display coordinate space.
4154TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4155 ui::Transform firstDisplayTransform;
4156 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4157 ui::Transform secondDisplayTransform;
4158 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4159
4160 std::vector<gui::DisplayInfo> displayInfos(2);
4161 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4162 displayInfos[0].transform = firstDisplayTransform;
4163 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4164 displayInfos[1].transform = secondDisplayTransform;
4165
4166 mDispatcher->onWindowInfosChanged({}, displayInfos);
4167
4168 // Enable InputFilter
4169 mDispatcher->setInputFilterEnabled(true);
4170
4171 // Ensure the correct transforms are used for the displays.
4172 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4173 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4174}
4175
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4177protected:
4178 virtual void SetUp() override {
4179 InputDispatcherTest::SetUp();
4180
4181 /**
4182 * We don't need to enable input filter to test the injected event policy, but we enabled it
4183 * here to make the tests more realistic, since this policy only matters when inputfilter is
4184 * on.
4185 */
4186 mDispatcher->setInputFilterEnabled(true);
4187
4188 std::shared_ptr<InputApplicationHandle> application =
4189 std::make_shared<FakeApplicationHandle>();
4190 mWindow =
4191 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4192
4193 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4194 mWindow->setFocusable(true);
4195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4196 setFocusedWindow(mWindow);
4197 mWindow->consumeFocusEvent(true);
4198 }
4199
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004200 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4201 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004202 KeyEvent event;
4203
4204 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4205 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4206 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4207 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4208 const int32_t additionalPolicyFlags =
4209 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004211 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004212 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4213 policyFlags | additionalPolicyFlags));
4214
4215 InputEvent* received = mWindow->consume();
4216 ASSERT_NE(nullptr, received);
4217 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004218 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4219 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4220 ASSERT_EQ(flags, keyEvent.getFlags());
4221 }
4222
4223 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4224 int32_t flags) {
4225 MotionEvent event;
4226 PointerProperties pointerProperties[1];
4227 PointerCoords pointerCoords[1];
4228 pointerProperties[0].clear();
4229 pointerProperties[0].id = 0;
4230 pointerCoords[0].clear();
4231 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4232 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4233
4234 ui::Transform identityTransform;
4235 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4236 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4237 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4238 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4239 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004240 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004241 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004242 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4243
4244 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004246 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004247 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4248 policyFlags | additionalPolicyFlags));
4249
4250 InputEvent* received = mWindow->consume();
4251 ASSERT_NE(nullptr, received);
4252 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4253 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4254 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4255 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004256 }
4257
4258private:
4259 sp<FakeWindowHandle> mWindow;
4260};
4261
4262TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004263 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4264 // filter. Without it, the event will no different from a regularly injected event, and the
4265 // injected device id will be overwritten.
4266 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4267 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268}
4269
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004270TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004271 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004272 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4273 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4274}
4275
4276TEST_F(InputFilterInjectionPolicyTest,
4277 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4278 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4279 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4280 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281}
4282
4283TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4284 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004285 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286}
4287
chaviwfd6d3512019-03-25 13:23:49 -07004288class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004289 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004290 InputDispatcherTest::SetUp();
4291
Chris Yea209fde2020-07-22 13:54:51 -07004292 std::shared_ptr<FakeApplicationHandle> application =
4293 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004294 mUnfocusedWindow =
4295 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004296 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004297
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004298 mFocusedWindow =
4299 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4300 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004301
4302 // Set focused application.
4303 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004304 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004305
4306 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004308 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004309 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004310 }
4311
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004312 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004313 InputDispatcherTest::TearDown();
4314
4315 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004316 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004317 }
4318
4319protected:
4320 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004321 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004322 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004323};
4324
4325// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4326// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4327// the onPointerDownOutsideFocus callback.
4328TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004330 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4331 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004332 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004333 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004334
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004335 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004336 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4337}
4338
4339// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4340// DOWN on the window that doesn't have focus. Ensure no window received the
4341// onPointerDownOutsideFocus callback.
4342TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004344 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004345 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004346 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004347
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004348 ASSERT_TRUE(mDispatcher->waitForIdle());
4349 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004350}
4351
4352// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4353// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4354TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4356 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004358 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004359
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004360 ASSERT_TRUE(mDispatcher->waitForIdle());
4361 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004362}
4363
4364// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4365// DOWN on the window that already has focus. Ensure no window received the
4366// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004367TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004369 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004370 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004371 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004372 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004373
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004374 ASSERT_TRUE(mDispatcher->waitForIdle());
4375 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004376}
4377
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004378// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4379// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4380TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4381 const MotionEvent event =
4382 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4383 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4384 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4385 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4386 .build();
4387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4389 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4390
4391 ASSERT_TRUE(mDispatcher->waitForIdle());
4392 mFakePolicy->assertOnPointerDownWasNotCalled();
4393 // Ensure that the unfocused window did not receive any FOCUS events.
4394 mUnfocusedWindow->assertNoEvents();
4395}
4396
chaviwaf87b3e2019-10-01 16:59:28 -07004397// These tests ensures we can send touch events to a single client when there are multiple input
4398// windows that point to the same client token.
4399class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4400 virtual void SetUp() override {
4401 InputDispatcherTest::SetUp();
4402
Chris Yea209fde2020-07-22 13:54:51 -07004403 std::shared_ptr<FakeApplicationHandle> application =
4404 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004405 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4406 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004407 mWindow1->setFrame(Rect(0, 0, 100, 100));
4408
4409 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4410 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004411 mWindow2->setFrame(Rect(100, 100, 200, 200));
4412
Arthur Hung72d8dc32020-03-28 00:48:39 +00004413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004414 }
4415
4416protected:
4417 sp<FakeWindowHandle> mWindow1;
4418 sp<FakeWindowHandle> mWindow2;
4419
4420 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004421 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004422 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4423 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004424 }
4425
4426 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4427 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004428 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004429 InputEvent* event = window->consume();
4430
4431 ASSERT_NE(nullptr, event) << name.c_str()
4432 << ": consumer should have returned non-NULL event.";
4433
4434 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4435 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4436 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4437
4438 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004439 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004440
4441 for (size_t i = 0; i < points.size(); i++) {
4442 float expectedX = points[i].x;
4443 float expectedY = points[i].y;
4444
4445 EXPECT_EQ(expectedX, motionEvent.getX(i))
4446 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4447 << ", got " << motionEvent.getX(i);
4448 EXPECT_EQ(expectedY, motionEvent.getY(i))
4449 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4450 << ", got " << motionEvent.getY(i);
4451 }
4452 }
chaviw9eaa22c2020-07-01 16:21:27 -07004453
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004454 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004455 std::vector<PointF> expectedPoints) {
4456 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4457 ADISPLAY_ID_DEFAULT, touchedPoints);
4458 mDispatcher->notifyMotion(&motionArgs);
4459
4460 // Always consume from window1 since it's the window that has the InputReceiver
4461 consumeMotionEvent(mWindow1, action, expectedPoints);
4462 }
chaviwaf87b3e2019-10-01 16:59:28 -07004463};
4464
4465TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4466 // Touch Window 1
4467 PointF touchedPoint = {10, 10};
4468 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004469 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004470
4471 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004472 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004473
4474 // Touch Window 2
4475 touchedPoint = {150, 150};
4476 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004477 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004478}
4479
chaviw9eaa22c2020-07-01 16:21:27 -07004480TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4481 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004482 mWindow2->setWindowScale(0.5f, 0.5f);
4483
4484 // Touch Window 1
4485 PointF touchedPoint = {10, 10};
4486 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004487 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004488 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004489 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004490
4491 // Touch Window 2
4492 touchedPoint = {150, 150};
4493 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004494 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4495 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004496
chaviw9eaa22c2020-07-01 16:21:27 -07004497 // Update the transform so rotation is set
4498 mWindow2->setWindowTransform(0, -1, 1, 0);
4499 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4500 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004501}
4502
chaviw9eaa22c2020-07-01 16:21:27 -07004503TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004504 mWindow2->setWindowScale(0.5f, 0.5f);
4505
4506 // Touch Window 1
4507 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4508 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004509 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004510
4511 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004512 touchedPoints.push_back(PointF{150, 150});
4513 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004514 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004515
chaviw9eaa22c2020-07-01 16:21:27 -07004516 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004517 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004518 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004519
chaviw9eaa22c2020-07-01 16:21:27 -07004520 // Update the transform so rotation is set for Window 2
4521 mWindow2->setWindowTransform(0, -1, 1, 0);
4522 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004523 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004524}
4525
chaviw9eaa22c2020-07-01 16:21:27 -07004526TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004527 mWindow2->setWindowScale(0.5f, 0.5f);
4528
4529 // Touch Window 1
4530 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4531 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004532 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004533
4534 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004535 touchedPoints.push_back(PointF{150, 150});
4536 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004537
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004538 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004539
4540 // Move both windows
4541 touchedPoints = {{20, 20}, {175, 175}};
4542 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4543 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4544
chaviw9eaa22c2020-07-01 16:21:27 -07004545 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004546
chaviw9eaa22c2020-07-01 16:21:27 -07004547 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004548 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004549 expectedPoints.pop_back();
4550
4551 // Touch Window 2
4552 mWindow2->setWindowTransform(0, -1, 1, 0);
4553 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004554 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004555
4556 // Move both windows
4557 touchedPoints = {{20, 20}, {175, 175}};
4558 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4559 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4560
4561 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004562}
4563
4564TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4565 mWindow1->setWindowScale(0.5f, 0.5f);
4566
4567 // Touch Window 1
4568 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4569 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004570 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004571
4572 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004573 touchedPoints.push_back(PointF{150, 150});
4574 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004575
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004576 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004577
4578 // Move both windows
4579 touchedPoints = {{20, 20}, {175, 175}};
4580 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4581 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4582
chaviw9eaa22c2020-07-01 16:21:27 -07004583 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004584}
4585
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004586class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4587 virtual void SetUp() override {
4588 InputDispatcherTest::SetUp();
4589
Chris Yea209fde2020-07-22 13:54:51 -07004590 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004591 mApplication->setDispatchingTimeout(20ms);
4592 mWindow =
4593 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4594 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004595 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004596 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004597
4598 // Set focused application.
4599 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4600
4601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004602 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004603 mWindow->consumeFocusEvent(true);
4604 }
4605
4606 virtual void TearDown() override {
4607 InputDispatcherTest::TearDown();
4608 mWindow.clear();
4609 }
4610
4611protected:
Chris Yea209fde2020-07-22 13:54:51 -07004612 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004613 sp<FakeWindowHandle> mWindow;
4614 static constexpr PointF WINDOW_LOCATION = {20, 20};
4615
4616 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4619 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004621 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4622 WINDOW_LOCATION));
4623 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004624
4625 sp<FakeWindowHandle> addSpyWindow() {
4626 sp<FakeWindowHandle> spy =
4627 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4628 spy->setTrustedOverlay(true);
4629 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004630 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004631 spy->setDispatchingTimeout(30ms);
4632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4633 return spy;
4634 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004635};
4636
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637// Send a tap and respond, which should not cause an ANR.
4638TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4639 tapOnWindow();
4640 mWindow->consumeMotionDown();
4641 mWindow->consumeMotionUp();
4642 ASSERT_TRUE(mDispatcher->waitForIdle());
4643 mFakePolicy->assertNotifyAnrWasNotCalled();
4644}
4645
4646// Send a regular key and respond, which should not cause an ANR.
4647TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4650 ASSERT_TRUE(mDispatcher->waitForIdle());
4651 mFakePolicy->assertNotifyAnrWasNotCalled();
4652}
4653
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004654TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4655 mWindow->setFocusable(false);
4656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4657 mWindow->consumeFocusEvent(false);
4658
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004660 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004661 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4662 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004664 // Key will not go to window because we have no focused window.
4665 // The 'no focused window' ANR timer should start instead.
4666
4667 // Now, the focused application goes away.
4668 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4669 // The key should get dropped and there should be no ANR.
4670
4671 ASSERT_TRUE(mDispatcher->waitForIdle());
4672 mFakePolicy->assertNotifyAnrWasNotCalled();
4673}
4674
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004675// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004676// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4677// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004678TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004680 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4681 WINDOW_LOCATION));
4682
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004683 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4684 ASSERT_TRUE(sequenceNum);
4685 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004686 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004687
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688 mWindow->finishEvent(*sequenceNum);
4689 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4690 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004691 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004692 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004693}
4694
4695// Send a key to the app and have the app not respond right away.
4696TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4697 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004699 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4700 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004701 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004702 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004703 ASSERT_TRUE(mDispatcher->waitForIdle());
4704}
4705
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004706// We have a focused application, but no focused window
4707TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004708 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4710 mWindow->consumeFocusEvent(false);
4711
4712 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004713 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4715 WINDOW_LOCATION));
4716 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4717 mDispatcher->waitForIdle();
4718 mFakePolicy->assertNotifyAnrWasNotCalled();
4719
4720 // Once a focused event arrives, we get an ANR for this application
4721 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4722 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004725 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004728 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729 ASSERT_TRUE(mDispatcher->waitForIdle());
4730}
4731
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004732/**
4733 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4734 * there will not be an ANR.
4735 */
4736TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4737 mWindow->setFocusable(false);
4738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4739 mWindow->consumeFocusEvent(false);
4740
4741 KeyEvent event;
4742 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4743 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4744
4745 // Define a valid key down event that is stale (too old).
4746 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4747 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4748 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4749
4750 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4751
4752 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004753 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004754 InputEventInjectionSync::WAIT_FOR_RESULT,
4755 INJECT_EVENT_TIMEOUT, policyFlags);
4756 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4757 << "Injection should fail because the event is stale";
4758
4759 ASSERT_TRUE(mDispatcher->waitForIdle());
4760 mFakePolicy->assertNotifyAnrWasNotCalled();
4761 mWindow->assertNoEvents();
4762}
4763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004765// Make sure that we don't notify policy twice about the same ANR.
4766TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004767 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4769 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770
4771 // Once a focused event arrives, we get an ANR for this application
4772 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4773 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004774 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004775 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004776 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004777 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 const std::chrono::duration appTimeout =
4779 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004780 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004782 std::this_thread::sleep_for(appTimeout);
4783 // ANR should not be raised again. It is up to policy to do that if it desires.
4784 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004786 // If we now get a focused window, the ANR should stop, but the policy handles that via
4787 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788 ASSERT_TRUE(mDispatcher->waitForIdle());
4789}
4790
4791// We have a focused application, but no focused window
4792TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004793 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4795 mWindow->consumeFocusEvent(false);
4796
4797 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4801 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802
4803 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004804 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805
4806 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004807 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 ASSERT_TRUE(mDispatcher->waitForIdle());
4809 mWindow->assertNoEvents();
4810}
4811
4812/**
4813 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4814 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4815 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4816 * the ANR mechanism should still work.
4817 *
4818 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4819 * DOWN event, while not responding on the second one.
4820 */
4821TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4822 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4823 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4824 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4825 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4826 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004827 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828
4829 // Now send ACTION_UP, with identical timestamp
4830 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4831 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4832 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4833 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835
4836 // We have now sent down and up. Let's consume first event and then ANR on the second.
4837 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4838 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004839 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840}
4841
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004842// A spy window can receive an ANR
4843TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4844 sp<FakeWindowHandle> spy = addSpyWindow();
4845
4846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4847 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4848 WINDOW_LOCATION));
4849 mWindow->consumeMotionDown();
4850
4851 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4852 ASSERT_TRUE(sequenceNum);
4853 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004854 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855
4856 spy->finishEvent(*sequenceNum);
4857 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4858 0 /*flags*/);
4859 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004860 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004861}
4862
4863// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004865TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4866 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4869 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004870 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872
4873 // Stuck on the ACTION_UP
4874 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004875 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004877 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004879 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4880 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881
4882 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4883 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004884 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004886 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887}
4888
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004889// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004891TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4892 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004893
4894 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004895 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4896 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004897
4898 mWindow->consumeMotionDown();
4899 // Stuck on the ACTION_UP
4900 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004901 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004903 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004905 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4906 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004907
4908 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4909 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004910 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004912 spy->assertNoEvents();
4913}
4914
4915TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4916 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4917
4918 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4919
4920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4921 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4922 WINDOW_LOCATION));
4923
4924 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4925 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4926 ASSERT_TRUE(consumeSeq);
4927
Prabir Pradhanedd96402022-02-15 01:46:16 -08004928 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004929
4930 monitor.finishEvent(*consumeSeq);
4931 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4932
4933 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004934 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935}
4936
4937// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4938// process events, you don't get an anr. When the window later becomes unresponsive again, you
4939// get an ANR again.
4940// 1. tap -> block on ACTION_UP -> receive ANR
4941// 2. consume all pending events (= queue becomes healthy again)
4942// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4943TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4944 tapOnWindow();
4945
4946 mWindow->consumeMotionDown();
4947 // Block on ACTION_UP
4948 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004949 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004950 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4951 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004952 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004953 mWindow->assertNoEvents();
4954
4955 tapOnWindow();
4956 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004957 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958 mWindow->consumeMotionUp();
4959
4960 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004961 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004962 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 mWindow->assertNoEvents();
4964}
4965
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004966// If a connection remains unresponsive for a while, make sure policy is only notified once about
4967// it.
4968TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4971 WINDOW_LOCATION));
4972
4973 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004974 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004976 // 'notifyConnectionUnresponsive' should only be called once per connection
4977 mFakePolicy->assertNotifyAnrWasNotCalled();
4978 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004979 mWindow->consumeMotionDown();
4980 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4981 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4982 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004983 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004984 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004985 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986}
4987
4988/**
4989 * If a window is processing a motion event, and then a key event comes in, the key event should
4990 * not to to the focused window until the motion is processed.
4991 *
4992 * Warning!!!
4993 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4994 * and the injection timeout that we specify when injecting the key.
4995 * We must have the injection timeout (10ms) be smaller than
4996 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4997 *
4998 * If that value changes, this test should also change.
4999 */
5000TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5001 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5003
5004 tapOnWindow();
5005 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5006 ASSERT_TRUE(downSequenceNum);
5007 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5008 ASSERT_TRUE(upSequenceNum);
5009 // Don't finish the events yet, and send a key
5010 // Injection will "succeed" because we will eventually give up and send the key to the focused
5011 // window even if motions are still being processed. But because the injection timeout is short,
5012 // we will receive INJECTION_TIMED_OUT as the result.
5013
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005014 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005015 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005016 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5017 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005018 // Key will not be sent to the window, yet, because the window is still processing events
5019 // and the key remains pending, waiting for the touch events to be processed
5020 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5021 ASSERT_FALSE(keySequenceNum);
5022
5023 std::this_thread::sleep_for(500ms);
5024 // if we wait long enough though, dispatcher will give up, and still send the key
5025 // to the focused window, even though we have not yet finished the motion event
5026 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5027 mWindow->finishEvent(*downSequenceNum);
5028 mWindow->finishEvent(*upSequenceNum);
5029}
5030
5031/**
5032 * If a window is processing a motion event, and then a key event comes in, the key event should
5033 * not go to the focused window until the motion is processed.
5034 * If then a new motion comes in, then the pending key event should be going to the currently
5035 * focused window right away.
5036 */
5037TEST_F(InputDispatcherSingleWindowAnr,
5038 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5039 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5041
5042 tapOnWindow();
5043 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5044 ASSERT_TRUE(downSequenceNum);
5045 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5046 ASSERT_TRUE(upSequenceNum);
5047 // Don't finish the events yet, and send a key
5048 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005050 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005051 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005052 // At this point, key is still pending, and should not be sent to the application yet.
5053 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5054 ASSERT_FALSE(keySequenceNum);
5055
5056 // Now tap down again. It should cause the pending key to go to the focused window right away.
5057 tapOnWindow();
5058 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5059 // the other events yet. We can finish events in any order.
5060 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5061 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5062 mWindow->consumeMotionDown();
5063 mWindow->consumeMotionUp();
5064 mWindow->assertNoEvents();
5065}
5066
5067class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5068 virtual void SetUp() override {
5069 InputDispatcherTest::SetUp();
5070
Chris Yea209fde2020-07-22 13:54:51 -07005071 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005072 mApplication->setDispatchingTimeout(10ms);
5073 mUnfocusedWindow =
5074 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5075 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005076 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005077 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005078
5079 mFocusedWindow =
5080 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005081 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005083
5084 // Set focused application.
5085 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005086 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005087
5088 // Expect one focus window exist in display.
5089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005090 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091 mFocusedWindow->consumeFocusEvent(true);
5092 }
5093
5094 virtual void TearDown() override {
5095 InputDispatcherTest::TearDown();
5096
5097 mUnfocusedWindow.clear();
5098 mFocusedWindow.clear();
5099 }
5100
5101protected:
Chris Yea209fde2020-07-22 13:54:51 -07005102 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005103 sp<FakeWindowHandle> mUnfocusedWindow;
5104 sp<FakeWindowHandle> mFocusedWindow;
5105 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5106 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5107 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5108
5109 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5110
5111 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5112
5113private:
5114 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5117 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005119 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5120 location));
5121 }
5122};
5123
5124// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5125// should be ANR'd first.
5126TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005127 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005128 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5129 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005130 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 mFocusedWindow->consumeMotionDown();
5132 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5133 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5134 // We consumed all events, so no ANR
5135 ASSERT_TRUE(mDispatcher->waitForIdle());
5136 mFakePolicy->assertNotifyAnrWasNotCalled();
5137
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005139 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5140 FOCUSED_WINDOW_LOCATION));
5141 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5142 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005143
5144 const std::chrono::duration timeout =
5145 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005146 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005147 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5148 // sequence to make it consistent
5149 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005150 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005151 mFocusedWindow->consumeMotionDown();
5152 // This cancel is generated because the connection was unresponsive
5153 mFocusedWindow->consumeMotionCancel();
5154 mFocusedWindow->assertNoEvents();
5155 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005156 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005157 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5158 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005159 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005160}
5161
5162// If we have 2 windows with identical timeouts that are both unresponsive,
5163// it doesn't matter which order they should have ANR.
5164// But we should receive ANR for both.
5165TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5166 // Set the timeout for unfocused window to match the focused window
5167 mUnfocusedWindow->setDispatchingTimeout(10ms);
5168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5169
5170 tapOnFocusedWindow();
5171 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005172 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5173 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5174 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005175
5176 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005177 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5178 mFocusedWindow->getToken() == anrConnectionToken2);
5179 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5180 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005181
5182 ASSERT_TRUE(mDispatcher->waitForIdle());
5183 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005184
5185 mFocusedWindow->consumeMotionDown();
5186 mFocusedWindow->consumeMotionUp();
5187 mUnfocusedWindow->consumeMotionOutside();
5188
Prabir Pradhanedd96402022-02-15 01:46:16 -08005189 sp<IBinder> responsiveToken1, responsiveToken2;
5190 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5191 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005192
5193 // Both applications should be marked as responsive, in any order
5194 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5195 mFocusedWindow->getToken() == responsiveToken2);
5196 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5197 mUnfocusedWindow->getToken() == responsiveToken2);
5198 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199}
5200
5201// If a window is already not responding, the second tap on the same window should be ignored.
5202// We should also log an error to account for the dropped event (not tested here).
5203// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5204TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5205 tapOnFocusedWindow();
5206 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5207 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5208 // Receive the events, but don't respond
5209 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5210 ASSERT_TRUE(downEventSequenceNum);
5211 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5212 ASSERT_TRUE(upEventSequenceNum);
5213 const std::chrono::duration timeout =
5214 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005215 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005216
5217 // Tap once again
5218 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005219 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5221 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005222 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5224 FOCUSED_WINDOW_LOCATION));
5225 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5226 // valid touch target
5227 mUnfocusedWindow->assertNoEvents();
5228
5229 // Consume the first tap
5230 mFocusedWindow->finishEvent(*downEventSequenceNum);
5231 mFocusedWindow->finishEvent(*upEventSequenceNum);
5232 ASSERT_TRUE(mDispatcher->waitForIdle());
5233 // The second tap did not go to the focused window
5234 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005235 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005236 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5237 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 mFakePolicy->assertNotifyAnrWasNotCalled();
5239}
5240
5241// If you tap outside of all windows, there will not be ANR
5242TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005243 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005244 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5245 LOCATION_OUTSIDE_ALL_WINDOWS));
5246 ASSERT_TRUE(mDispatcher->waitForIdle());
5247 mFakePolicy->assertNotifyAnrWasNotCalled();
5248}
5249
5250// Since the focused window is paused, tapping on it should not produce any events
5251TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5252 mFocusedWindow->setPaused(true);
5253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5254
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005255 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5257 FOCUSED_WINDOW_LOCATION));
5258
5259 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5260 ASSERT_TRUE(mDispatcher->waitForIdle());
5261 // Should not ANR because the window is paused, and touches shouldn't go to it
5262 mFakePolicy->assertNotifyAnrWasNotCalled();
5263
5264 mFocusedWindow->assertNoEvents();
5265 mUnfocusedWindow->assertNoEvents();
5266}
5267
5268/**
5269 * If a window is processing a motion event, and then a key event comes in, the key event should
5270 * not to to the focused window until the motion is processed.
5271 * If a different window becomes focused at this time, the key should go to that window instead.
5272 *
5273 * Warning!!!
5274 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5275 * and the injection timeout that we specify when injecting the key.
5276 * We must have the injection timeout (10ms) be smaller than
5277 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5278 *
5279 * If that value changes, this test should also change.
5280 */
5281TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5282 // Set a long ANR timeout to prevent it from triggering
5283 mFocusedWindow->setDispatchingTimeout(2s);
5284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5285
5286 tapOnUnfocusedWindow();
5287 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5288 ASSERT_TRUE(downSequenceNum);
5289 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5290 ASSERT_TRUE(upSequenceNum);
5291 // Don't finish the events yet, and send a key
5292 // Injection will succeed because we will eventually give up and send the key to the focused
5293 // window even if motions are still being processed.
5294
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005295 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005296 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005297 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005299 // Key will not be sent to the window, yet, because the window is still processing events
5300 // and the key remains pending, waiting for the touch events to be processed
5301 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5302 ASSERT_FALSE(keySequenceNum);
5303
5304 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005305 mFocusedWindow->setFocusable(false);
5306 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005308 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005309
5310 // Focus events should precede the key events
5311 mUnfocusedWindow->consumeFocusEvent(true);
5312 mFocusedWindow->consumeFocusEvent(false);
5313
5314 // Finish the tap events, which should unblock dispatcher
5315 mUnfocusedWindow->finishEvent(*downSequenceNum);
5316 mUnfocusedWindow->finishEvent(*upSequenceNum);
5317
5318 // Now that all queues are cleared and no backlog in the connections, the key event
5319 // can finally go to the newly focused "mUnfocusedWindow".
5320 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5321 mFocusedWindow->assertNoEvents();
5322 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005323 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005324}
5325
5326// When the touch stream is split across 2 windows, and one of them does not respond,
5327// then ANR should be raised and the touch should be canceled for the unresponsive window.
5328// The other window should not be affected by that.
5329TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5330 // Touch Window 1
5331 NotifyMotionArgs motionArgs =
5332 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5333 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5334 mDispatcher->notifyMotion(&motionArgs);
5335 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5336 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5337
5338 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005339 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5340 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341 mDispatcher->notifyMotion(&motionArgs);
5342
5343 const std::chrono::duration timeout =
5344 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005345 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005346
5347 mUnfocusedWindow->consumeMotionDown();
5348 mFocusedWindow->consumeMotionDown();
5349 // Focused window may or may not receive ACTION_MOVE
5350 // But it should definitely receive ACTION_CANCEL due to the ANR
5351 InputEvent* event;
5352 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5353 ASSERT_TRUE(moveOrCancelSequenceNum);
5354 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5355 ASSERT_NE(nullptr, event);
5356 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5357 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5358 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5359 mFocusedWindow->consumeMotionCancel();
5360 } else {
5361 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5362 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005363 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005364 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5365 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005366
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005367 mUnfocusedWindow->assertNoEvents();
5368 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005369 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005370}
5371
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005372/**
5373 * If we have no focused window, and a key comes in, we start the ANR timer.
5374 * The focused application should add a focused window before the timer runs out to prevent ANR.
5375 *
5376 * If the user touches another application during this time, the key should be dropped.
5377 * Next, if a new focused window comes in, without toggling the focused application,
5378 * then no ANR should occur.
5379 *
5380 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5381 * but in some cases the policy may not update the focused application.
5382 */
5383TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5384 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5385 std::make_shared<FakeApplicationHandle>();
5386 focusedApplication->setDispatchingTimeout(60ms);
5387 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5388 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5389 mFocusedWindow->setFocusable(false);
5390
5391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5392 mFocusedWindow->consumeFocusEvent(false);
5393
5394 // Send a key. The ANR timer should start because there is no focused window.
5395 // 'focusedApplication' will get blamed if this timer completes.
5396 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005397 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005398 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005399 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5400 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005402
5403 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5404 // then the injected touches won't cause the focused event to get dropped.
5405 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5406 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5407 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5408 // For this test, it means that the key would get delivered to the window once it becomes
5409 // focused.
5410 std::this_thread::sleep_for(10ms);
5411
5412 // Touch unfocused window. This should force the pending key to get dropped.
5413 NotifyMotionArgs motionArgs =
5414 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5415 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5416 mDispatcher->notifyMotion(&motionArgs);
5417
5418 // We do not consume the motion right away, because that would require dispatcher to first
5419 // process (== drop) the key event, and by that time, ANR will be raised.
5420 // Set the focused window first.
5421 mFocusedWindow->setFocusable(true);
5422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5423 setFocusedWindow(mFocusedWindow);
5424 mFocusedWindow->consumeFocusEvent(true);
5425 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5426 // to another application. This could be a bug / behaviour in the policy.
5427
5428 mUnfocusedWindow->consumeMotionDown();
5429
5430 ASSERT_TRUE(mDispatcher->waitForIdle());
5431 // Should not ANR because we actually have a focused window. It was just added too slowly.
5432 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5433}
5434
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005435// These tests ensure we cannot send touch events to a window that's positioned behind a window
5436// that has feature NO_INPUT_CHANNEL.
5437// Layout:
5438// Top (closest to user)
5439// mNoInputWindow (above all windows)
5440// mBottomWindow
5441// Bottom (furthest from user)
5442class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5443 virtual void SetUp() override {
5444 InputDispatcherTest::SetUp();
5445
5446 mApplication = std::make_shared<FakeApplicationHandle>();
5447 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5448 "Window without input channel", ADISPLAY_ID_DEFAULT,
5449 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5450
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005451 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005452 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5453 // It's perfectly valid for this window to not have an associated input channel
5454
5455 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5456 ADISPLAY_ID_DEFAULT);
5457 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5458
5459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5460 }
5461
5462protected:
5463 std::shared_ptr<FakeApplicationHandle> mApplication;
5464 sp<FakeWindowHandle> mNoInputWindow;
5465 sp<FakeWindowHandle> mBottomWindow;
5466};
5467
5468TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5469 PointF touchedPoint = {10, 10};
5470
5471 NotifyMotionArgs motionArgs =
5472 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5473 ADISPLAY_ID_DEFAULT, {touchedPoint});
5474 mDispatcher->notifyMotion(&motionArgs);
5475
5476 mNoInputWindow->assertNoEvents();
5477 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5478 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5479 // and therefore should prevent mBottomWindow from receiving touches
5480 mBottomWindow->assertNoEvents();
5481}
5482
5483/**
5484 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5485 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5486 */
5487TEST_F(InputDispatcherMultiWindowOcclusionTests,
5488 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5489 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5490 "Window with input channel and NO_INPUT_CHANNEL",
5491 ADISPLAY_ID_DEFAULT);
5492
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005493 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005494 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5496
5497 PointF touchedPoint = {10, 10};
5498
5499 NotifyMotionArgs motionArgs =
5500 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5501 ADISPLAY_ID_DEFAULT, {touchedPoint});
5502 mDispatcher->notifyMotion(&motionArgs);
5503
5504 mNoInputWindow->assertNoEvents();
5505 mBottomWindow->assertNoEvents();
5506}
5507
Vishnu Nair958da932020-08-21 17:12:37 -07005508class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5509protected:
5510 std::shared_ptr<FakeApplicationHandle> mApp;
5511 sp<FakeWindowHandle> mWindow;
5512 sp<FakeWindowHandle> mMirror;
5513
5514 virtual void SetUp() override {
5515 InputDispatcherTest::SetUp();
5516 mApp = std::make_shared<FakeApplicationHandle>();
5517 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5518 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5519 mWindow->getToken());
5520 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5521 mWindow->setFocusable(true);
5522 mMirror->setFocusable(true);
5523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5524 }
5525};
5526
5527TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5528 // Request focus on a mirrored window
5529 setFocusedWindow(mMirror);
5530
5531 // window gets focused
5532 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5534 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005535 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5536}
5537
5538// A focused & mirrored window remains focused only if the window and its mirror are both
5539// focusable.
5540TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5541 setFocusedWindow(mMirror);
5542
5543 // window gets focused
5544 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5546 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005547 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5549 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005550 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5551
5552 mMirror->setFocusable(false);
5553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5554
5555 // window loses focus since one of the windows associated with the token in not focusable
5556 mWindow->consumeFocusEvent(false);
5557
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005558 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5559 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005560 mWindow->assertNoEvents();
5561}
5562
5563// A focused & mirrored window remains focused until the window and its mirror both become
5564// invisible.
5565TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
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 mMirror->setVisible(false);
5578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, 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 mWindow->setVisible(false);
5588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5589
5590 // window loses focus only after all windows associated with the token become invisible.
5591 mWindow->consumeFocusEvent(false);
5592
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005593 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5594 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005595 mWindow->assertNoEvents();
5596}
5597
5598// A focused & mirrored window remains focused until both windows are removed.
5599TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5600 setFocusedWindow(mMirror);
5601
5602 // window gets focused
5603 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5605 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005606 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5608 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005609 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5610
5611 // single window is removed but the window token remains focused
5612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5613
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5615 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005616 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5618 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005619 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5620
5621 // Both windows are removed
5622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5623 mWindow->consumeFocusEvent(false);
5624
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005625 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5626 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005627 mWindow->assertNoEvents();
5628}
5629
5630// Focus request can be pending until one window becomes visible.
5631TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5632 // Request focus on an invisible mirror.
5633 mWindow->setVisible(false);
5634 mMirror->setVisible(false);
5635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5636 setFocusedWindow(mMirror);
5637
5638 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005640 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005641 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005642
5643 mMirror->setVisible(true);
5644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5645
5646 // window gets focused
5647 mWindow->consumeFocusEvent(true);
5648 // window gets the pending key event
5649 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5650}
Prabir Pradhan99987712020-11-10 18:43:05 -08005651
5652class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5653protected:
5654 std::shared_ptr<FakeApplicationHandle> mApp;
5655 sp<FakeWindowHandle> mWindow;
5656 sp<FakeWindowHandle> mSecondWindow;
5657
5658 void SetUp() override {
5659 InputDispatcherTest::SetUp();
5660 mApp = std::make_shared<FakeApplicationHandle>();
5661 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5662 mWindow->setFocusable(true);
5663 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5664 mSecondWindow->setFocusable(true);
5665
5666 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5668
5669 setFocusedWindow(mWindow);
5670 mWindow->consumeFocusEvent(true);
5671 }
5672
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005673 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5674 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005675 mDispatcher->notifyPointerCaptureChanged(&args);
5676 }
5677
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005678 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5679 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005680 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005681 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5682 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005683 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005684 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005685 }
5686};
5687
5688TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5689 // Ensure that capture cannot be obtained for unfocused windows.
5690 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5691 mFakePolicy->assertSetPointerCaptureNotCalled();
5692 mSecondWindow->assertNoEvents();
5693
5694 // Ensure that capture can be enabled from the focus window.
5695 requestAndVerifyPointerCapture(mWindow, true);
5696
5697 // Ensure that capture cannot be disabled from a window that does not have capture.
5698 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5699 mFakePolicy->assertSetPointerCaptureNotCalled();
5700
5701 // Ensure that capture can be disabled from the window with capture.
5702 requestAndVerifyPointerCapture(mWindow, false);
5703}
5704
5705TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005706 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005707
5708 setFocusedWindow(mSecondWindow);
5709
5710 // Ensure that the capture disabled event was sent first.
5711 mWindow->consumeCaptureEvent(false);
5712 mWindow->consumeFocusEvent(false);
5713 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005714 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005715
5716 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005717 notifyPointerCaptureChanged({});
5718 notifyPointerCaptureChanged(request);
5719 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005720 mWindow->assertNoEvents();
5721 mSecondWindow->assertNoEvents();
5722 mFakePolicy->assertSetPointerCaptureNotCalled();
5723}
5724
5725TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005726 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005727
5728 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005729 notifyPointerCaptureChanged({});
5730 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005731
5732 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005733 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005734 mWindow->consumeCaptureEvent(false);
5735 mWindow->assertNoEvents();
5736}
5737
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005738TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5739 requestAndVerifyPointerCapture(mWindow, true);
5740
5741 // The first window loses focus.
5742 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005743 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005744 mWindow->consumeCaptureEvent(false);
5745
5746 // Request Pointer Capture from the second window before the notification from InputReader
5747 // arrives.
5748 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005749 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005750
5751 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005752 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005753
5754 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005755 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005756
5757 mSecondWindow->consumeFocusEvent(true);
5758 mSecondWindow->consumeCaptureEvent(true);
5759}
5760
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005761TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5762 // App repeatedly enables and disables capture.
5763 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5764 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5765 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5766 mFakePolicy->assertSetPointerCaptureCalled(false);
5767 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5768 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5769
5770 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5771 // first request is now stale, this should do nothing.
5772 notifyPointerCaptureChanged(firstRequest);
5773 mWindow->assertNoEvents();
5774
5775 // InputReader notifies that the second request was enabled.
5776 notifyPointerCaptureChanged(secondRequest);
5777 mWindow->consumeCaptureEvent(true);
5778}
5779
Prabir Pradhan7092e262022-05-03 16:51:09 +00005780TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5781 requestAndVerifyPointerCapture(mWindow, true);
5782
5783 // App toggles pointer capture off and on.
5784 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5785 mFakePolicy->assertSetPointerCaptureCalled(false);
5786
5787 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5788 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5789
5790 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5791 // preceding "disable" request.
5792 notifyPointerCaptureChanged(enableRequest);
5793
5794 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5795 // any notifications.
5796 mWindow->assertNoEvents();
5797}
5798
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005799class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5800protected:
5801 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005802
5803 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5804 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5805
5806 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5807 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5808
5809 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5810 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5811 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5812 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5813 MAXIMUM_OBSCURING_OPACITY);
5814
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005815 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005816 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005817 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005818
5819 sp<FakeWindowHandle> mTouchWindow;
5820
5821 virtual void SetUp() override {
5822 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005823 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005824 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5825 }
5826
5827 virtual void TearDown() override {
5828 InputDispatcherTest::TearDown();
5829 mTouchWindow.clear();
5830 }
5831
chaviw3277faf2021-05-19 16:45:23 -05005832 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5833 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005834 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005835 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005836 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005837 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005838 return window;
5839 }
5840
5841 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5842 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5843 sp<FakeWindowHandle> window =
5844 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5845 // Generate an arbitrary PID based on the UID
5846 window->setOwnerInfo(1777 + (uid % 10000), uid);
5847 return window;
5848 }
5849
5850 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5851 NotifyMotionArgs args =
5852 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5853 ADISPLAY_ID_DEFAULT, points);
5854 mDispatcher->notifyMotion(&args);
5855 }
5856};
5857
5858TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005859 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005860 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005862
5863 touch();
5864
5865 mTouchWindow->assertNoEvents();
5866}
5867
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005868TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005869 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5870 const sp<FakeWindowHandle>& w =
5871 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5873
5874 touch();
5875
5876 mTouchWindow->assertNoEvents();
5877}
5878
5879TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005880 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5881 const sp<FakeWindowHandle>& w =
5882 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5884
5885 touch();
5886
5887 w->assertNoEvents();
5888}
5889
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005890TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005891 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005893
5894 touch();
5895
5896 mTouchWindow->consumeAnyMotionDown();
5897}
5898
5899TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005900 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005901 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005902 w->setFrame(Rect(0, 0, 50, 50));
5903 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005904
5905 touch({PointF{100, 100}});
5906
5907 mTouchWindow->consumeAnyMotionDown();
5908}
5909
5910TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005911 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005912 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5914
5915 touch();
5916
5917 mTouchWindow->consumeAnyMotionDown();
5918}
5919
5920TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5921 const sp<FakeWindowHandle>& w =
5922 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005924
5925 touch();
5926
5927 mTouchWindow->consumeAnyMotionDown();
5928}
5929
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005930TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5931 const sp<FakeWindowHandle>& w =
5932 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5934
5935 touch();
5936
5937 w->assertNoEvents();
5938}
5939
5940/**
5941 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5942 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5943 * window, the occluding window will still receive ACTION_OUTSIDE event.
5944 */
5945TEST_F(InputDispatcherUntrustedTouchesTest,
5946 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5947 const sp<FakeWindowHandle>& w =
5948 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005949 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5951
5952 touch();
5953
5954 w->consumeMotionOutside();
5955}
5956
5957TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5958 const sp<FakeWindowHandle>& w =
5959 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005960 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005961 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5962
5963 touch();
5964
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005965 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005966}
5967
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005968TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005969 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005970 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5971 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005972 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5973
5974 touch();
5975
5976 mTouchWindow->consumeAnyMotionDown();
5977}
5978
5979TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5980 const sp<FakeWindowHandle>& w =
5981 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5982 MAXIMUM_OBSCURING_OPACITY);
5983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005984
5985 touch();
5986
5987 mTouchWindow->consumeAnyMotionDown();
5988}
5989
5990TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005991 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005992 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5993 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5995
5996 touch();
5997
5998 mTouchWindow->assertNoEvents();
5999}
6000
6001TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6002 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6003 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006004 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6005 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006006 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006007 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6008 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6010
6011 touch();
6012
6013 mTouchWindow->assertNoEvents();
6014}
6015
6016TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6017 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6018 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006019 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6020 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006021 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006022 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6023 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6025
6026 touch();
6027
6028 mTouchWindow->consumeAnyMotionDown();
6029}
6030
6031TEST_F(InputDispatcherUntrustedTouchesTest,
6032 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6033 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006034 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6035 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006036 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006037 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6038 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6040
6041 touch();
6042
6043 mTouchWindow->consumeAnyMotionDown();
6044}
6045
6046TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6047 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006048 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6049 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006050 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006051 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6052 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006054
6055 touch();
6056
6057 mTouchWindow->assertNoEvents();
6058}
6059
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006060TEST_F(InputDispatcherUntrustedTouchesTest,
6061 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6062 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006063 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6064 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006065 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006066 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6067 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6069
6070 touch();
6071
6072 mTouchWindow->assertNoEvents();
6073}
6074
6075TEST_F(InputDispatcherUntrustedTouchesTest,
6076 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6077 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006078 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6079 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006080 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006081 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6082 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6084
6085 touch();
6086
6087 mTouchWindow->consumeAnyMotionDown();
6088}
6089
6090TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6091 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006092 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6093 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6095
6096 touch();
6097
6098 mTouchWindow->consumeAnyMotionDown();
6099}
6100
6101TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6102 const sp<FakeWindowHandle>& w =
6103 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6105
6106 touch();
6107
6108 mTouchWindow->consumeAnyMotionDown();
6109}
6110
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006111TEST_F(InputDispatcherUntrustedTouchesTest,
6112 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6113 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6114 const sp<FakeWindowHandle>& w =
6115 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6117
6118 touch();
6119
6120 mTouchWindow->assertNoEvents();
6121}
6122
6123TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6124 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6125 const sp<FakeWindowHandle>& w =
6126 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6128
6129 touch();
6130
6131 mTouchWindow->consumeAnyMotionDown();
6132}
6133
6134TEST_F(InputDispatcherUntrustedTouchesTest,
6135 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6136 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6137 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006138 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6139 OPACITY_ABOVE_THRESHOLD);
6140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6141
6142 touch();
6143
6144 mTouchWindow->consumeAnyMotionDown();
6145}
6146
6147TEST_F(InputDispatcherUntrustedTouchesTest,
6148 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6149 const sp<FakeWindowHandle>& w1 =
6150 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6151 OPACITY_BELOW_THRESHOLD);
6152 const sp<FakeWindowHandle>& w2 =
6153 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6154 OPACITY_BELOW_THRESHOLD);
6155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6156
6157 touch();
6158
6159 mTouchWindow->assertNoEvents();
6160}
6161
6162/**
6163 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6164 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6165 * (which alone would result in allowing touches) does not affect the blocking behavior.
6166 */
6167TEST_F(InputDispatcherUntrustedTouchesTest,
6168 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6169 const sp<FakeWindowHandle>& wB =
6170 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6171 OPACITY_BELOW_THRESHOLD);
6172 const sp<FakeWindowHandle>& wC =
6173 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6174 OPACITY_BELOW_THRESHOLD);
6175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6176
6177 touch();
6178
6179 mTouchWindow->assertNoEvents();
6180}
6181
6182/**
6183 * This test is testing that a window from a different UID but with same application token doesn't
6184 * block the touch. Apps can share the application token for close UI collaboration for example.
6185 */
6186TEST_F(InputDispatcherUntrustedTouchesTest,
6187 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6188 const sp<FakeWindowHandle>& w =
6189 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6190 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6192
6193 touch();
6194
6195 mTouchWindow->consumeAnyMotionDown();
6196}
6197
arthurhungb89ccb02020-12-30 16:19:01 +08006198class InputDispatcherDragTests : public InputDispatcherTest {
6199protected:
6200 std::shared_ptr<FakeApplicationHandle> mApp;
6201 sp<FakeWindowHandle> mWindow;
6202 sp<FakeWindowHandle> mSecondWindow;
6203 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006204 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006205 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6206 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006207
6208 void SetUp() override {
6209 InputDispatcherTest::SetUp();
6210 mApp = std::make_shared<FakeApplicationHandle>();
6211 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6212 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006213
6214 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6215 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006216
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006217 mSpyWindow = new FakeWindowHandle(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
6218 mSpyWindow->setSpy(true);
6219 mSpyWindow->setTrustedOverlay(true);
6220 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6221
arthurhungb89ccb02020-12-30 16:19:01 +08006222 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006224 }
6225
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006226 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6227 switch (fromSource) {
6228 case AINPUT_SOURCE_TOUCHSCREEN:
6229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6230 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6231 ADISPLAY_ID_DEFAULT, {50, 50}))
6232 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6233 break;
6234 case AINPUT_SOURCE_STYLUS:
6235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6236 injectMotionEvent(
6237 mDispatcher,
6238 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6239 AINPUT_SOURCE_STYLUS)
6240 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6241 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6242 .x(50)
6243 .y(50))
6244 .build()));
6245 break;
6246 case AINPUT_SOURCE_MOUSE:
6247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6248 injectMotionEvent(
6249 mDispatcher,
6250 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6251 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6252 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6253 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6254 .x(50)
6255 .y(50))
6256 .build()));
6257 break;
6258 default:
6259 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6260 }
arthurhungb89ccb02020-12-30 16:19:01 +08006261
6262 // Window should receive motion event.
6263 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006264 // Spy window should also receive motion event
6265 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006266 }
6267
6268 // Start performing drag, we will create a drag window and transfer touch to it.
6269 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6270 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006271 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006272 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006273 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006274 }
arthurhungb89ccb02020-12-30 16:19:01 +08006275
6276 // The drag window covers the entire display
6277 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006278 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006279 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006280 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006281
6282 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006283 bool transferred =
6284 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6285 true /* isDragDrop */);
6286 if (transferred) {
6287 mWindow->consumeMotionCancel();
6288 mDragWindow->consumeMotionDown();
6289 }
6290 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006291 }
6292};
6293
6294TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006295 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006296
6297 // Move on window.
6298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6299 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6300 ADISPLAY_ID_DEFAULT, {50, 50}))
6301 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6302 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6303 mWindow->consumeDragEvent(false, 50, 50);
6304 mSecondWindow->assertNoEvents();
6305
6306 // Move to another window.
6307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6308 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6309 ADISPLAY_ID_DEFAULT, {150, 50}))
6310 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6311 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6312 mWindow->consumeDragEvent(true, 150, 50);
6313 mSecondWindow->consumeDragEvent(false, 50, 50);
6314
6315 // Move back to original window.
6316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6317 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6318 ADISPLAY_ID_DEFAULT, {50, 50}))
6319 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6320 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6321 mWindow->consumeDragEvent(false, 50, 50);
6322 mSecondWindow->consumeDragEvent(true, -50, 50);
6323
6324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6325 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6327 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6328 mWindow->assertNoEvents();
6329 mSecondWindow->assertNoEvents();
6330}
6331
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006332TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006333 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006334
6335 // No cancel event after drag start
6336 mSpyWindow->assertNoEvents();
6337
6338 const MotionEvent secondFingerDownEvent =
6339 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6340 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6341 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6342 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6343 .build();
6344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6345 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6346 InputEventInjectionSync::WAIT_FOR_RESULT))
6347 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6348
6349 // Receives cancel for first pointer after next pointer down
6350 mSpyWindow->consumeMotionCancel();
6351 mSpyWindow->consumeMotionDown();
6352
6353 mSpyWindow->assertNoEvents();
6354}
6355
arthurhungf452d0b2021-01-06 00:19:52 +08006356TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006357 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006358
6359 // Move on window.
6360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6361 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6362 ADISPLAY_ID_DEFAULT, {50, 50}))
6363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6364 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6365 mWindow->consumeDragEvent(false, 50, 50);
6366 mSecondWindow->assertNoEvents();
6367
6368 // Move to another window.
6369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6370 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6371 ADISPLAY_ID_DEFAULT, {150, 50}))
6372 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6373 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6374 mWindow->consumeDragEvent(true, 150, 50);
6375 mSecondWindow->consumeDragEvent(false, 50, 50);
6376
6377 // drop to another window.
6378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6379 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6380 {150, 50}))
6381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6382 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6383 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6384 mWindow->assertNoEvents();
6385 mSecondWindow->assertNoEvents();
6386}
6387
arthurhung6d4bed92021-03-17 11:59:33 +08006388TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006389 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006390
6391 // Move on window and keep button pressed.
6392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6393 injectMotionEvent(mDispatcher,
6394 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6395 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6396 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6397 .x(50)
6398 .y(50))
6399 .build()))
6400 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6401 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6402 mWindow->consumeDragEvent(false, 50, 50);
6403 mSecondWindow->assertNoEvents();
6404
6405 // Move to another window and release button, expect to drop item.
6406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6407 injectMotionEvent(mDispatcher,
6408 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6409 .buttonState(0)
6410 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6411 .x(150)
6412 .y(50))
6413 .build()))
6414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6415 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6416 mWindow->assertNoEvents();
6417 mSecondWindow->assertNoEvents();
6418 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6419
6420 // nothing to the window.
6421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6422 injectMotionEvent(mDispatcher,
6423 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6424 .buttonState(0)
6425 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6426 .x(150)
6427 .y(50))
6428 .build()))
6429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6430 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6431 mWindow->assertNoEvents();
6432 mSecondWindow->assertNoEvents();
6433}
6434
Arthur Hung54745652022-04-20 07:17:41 +00006435TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006436 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006437
6438 // Set second window invisible.
6439 mSecondWindow->setVisible(false);
6440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6441
6442 // Move on window.
6443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6444 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6445 ADISPLAY_ID_DEFAULT, {50, 50}))
6446 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6447 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6448 mWindow->consumeDragEvent(false, 50, 50);
6449 mSecondWindow->assertNoEvents();
6450
6451 // Move to another window.
6452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6453 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6454 ADISPLAY_ID_DEFAULT, {150, 50}))
6455 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6456 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6457 mWindow->consumeDragEvent(true, 150, 50);
6458 mSecondWindow->assertNoEvents();
6459
6460 // drop to another window.
6461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6462 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6463 {150, 50}))
6464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6465 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6466 mFakePolicy->assertDropTargetEquals(nullptr);
6467 mWindow->assertNoEvents();
6468 mSecondWindow->assertNoEvents();
6469}
6470
Arthur Hung54745652022-04-20 07:17:41 +00006471TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006472 // Ensure window could track pointerIds if it didn't support split touch.
6473 mWindow->setPreventSplitting(true);
6474
Arthur Hung54745652022-04-20 07:17:41 +00006475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6476 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6477 {50, 50}))
6478 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6479 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6480
6481 const MotionEvent secondFingerDownEvent =
6482 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6483 .displayId(ADISPLAY_ID_DEFAULT)
6484 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6485 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6486 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6487 .build();
6488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6489 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6490 InputEventInjectionSync::WAIT_FOR_RESULT))
6491 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6492 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6493
6494 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006495 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006496}
6497
6498TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6499 // First down on second window.
6500 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6501 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6502 {150, 50}))
6503 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6504
6505 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6506
6507 // Second down on first window.
6508 const MotionEvent secondFingerDownEvent =
6509 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6510 .displayId(ADISPLAY_ID_DEFAULT)
6511 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6512 .pointer(
6513 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6514 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6515 .build();
6516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6517 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6518 InputEventInjectionSync::WAIT_FOR_RESULT))
6519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6520 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6521
6522 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006523 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006524
6525 // Move on window.
6526 const MotionEvent secondFingerMoveEvent =
6527 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6528 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6529 .pointer(
6530 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6531 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6532 .build();
6533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6534 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6535 InputEventInjectionSync::WAIT_FOR_RESULT));
6536 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6537 mWindow->consumeDragEvent(false, 50, 50);
6538 mSecondWindow->consumeMotionMove();
6539
6540 // Release the drag pointer should perform drop.
6541 const MotionEvent secondFingerUpEvent =
6542 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6543 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6544 .pointer(
6545 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6546 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6547 .build();
6548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6549 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6550 InputEventInjectionSync::WAIT_FOR_RESULT));
6551 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6552 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6553 mWindow->assertNoEvents();
6554 mSecondWindow->consumeMotionMove();
6555}
6556
Arthur Hung3915c1f2022-05-31 07:17:17 +00006557TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006558 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006559
6560 // Update window of second display.
6561 sp<FakeWindowHandle> windowInSecondary =
6562 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6563 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6564
6565 // Let second display has a touch state.
6566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6567 injectMotionEvent(mDispatcher,
6568 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6569 AINPUT_SOURCE_TOUCHSCREEN)
6570 .displayId(SECOND_DISPLAY_ID)
6571 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6572 .x(100)
6573 .y(100))
6574 .build()));
6575 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6576 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6577 // Update window again.
6578 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6579
6580 // Move on window.
6581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6582 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6583 ADISPLAY_ID_DEFAULT, {50, 50}))
6584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6585 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6586 mWindow->consumeDragEvent(false, 50, 50);
6587 mSecondWindow->assertNoEvents();
6588
6589 // Move to another window.
6590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6591 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6592 ADISPLAY_ID_DEFAULT, {150, 50}))
6593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6594 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6595 mWindow->consumeDragEvent(true, 150, 50);
6596 mSecondWindow->consumeDragEvent(false, 50, 50);
6597
6598 // drop to another window.
6599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6600 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6601 {150, 50}))
6602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6603 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6604 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6605 mWindow->assertNoEvents();
6606 mSecondWindow->assertNoEvents();
6607}
6608
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006609TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6610 startDrag(true, AINPUT_SOURCE_MOUSE);
6611 // Move on window.
6612 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6613 injectMotionEvent(mDispatcher,
6614 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6615 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6616 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6617 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6618 .x(50)
6619 .y(50))
6620 .build()))
6621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6622 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6623 mWindow->consumeDragEvent(false, 50, 50);
6624 mSecondWindow->assertNoEvents();
6625
6626 // Move to another window.
6627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6628 injectMotionEvent(mDispatcher,
6629 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6630 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6631 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6632 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6633 .x(150)
6634 .y(50))
6635 .build()))
6636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6637 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6638 mWindow->consumeDragEvent(true, 150, 50);
6639 mSecondWindow->consumeDragEvent(false, 50, 50);
6640
6641 // drop to another window.
6642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6643 injectMotionEvent(mDispatcher,
6644 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6645 .buttonState(0)
6646 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6647 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6648 .x(150)
6649 .y(50))
6650 .build()))
6651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6652 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6653 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6654 mWindow->assertNoEvents();
6655 mSecondWindow->assertNoEvents();
6656}
6657
Vishnu Nair062a8672021-09-03 16:07:44 -07006658class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6659
6660TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6662 sp<FakeWindowHandle> window =
6663 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006664 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006665 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6666 window->setFocusable(true);
6667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {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 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006683 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6685
6686 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6687 mDispatcher->notifyKey(&keyArgs);
6688 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6689
6690 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6691 ADISPLAY_ID_DEFAULT);
6692 mDispatcher->notifyMotion(&motionArgs);
6693 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6694 window->assertNoEvents();
6695}
6696
6697TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6698 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6699 std::make_shared<FakeApplicationHandle>();
6700 sp<FakeWindowHandle> obscuringWindow =
6701 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6702 ADISPLAY_ID_DEFAULT);
6703 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6704 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006705 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006706 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6707 sp<FakeWindowHandle> window =
6708 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006709 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006710 window->setOwnerInfo(222, 222);
6711 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6712 window->setFocusable(true);
6713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6714 setFocusedWindow(window);
6715 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6716
6717 // With the flag set, window should not get any input
6718 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6719 mDispatcher->notifyKey(&keyArgs);
6720 window->assertNoEvents();
6721
6722 NotifyMotionArgs motionArgs =
6723 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6724 ADISPLAY_ID_DEFAULT);
6725 mDispatcher->notifyMotion(&motionArgs);
6726 window->assertNoEvents();
6727
6728 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006729 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6731
6732 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6733 mDispatcher->notifyKey(&keyArgs);
6734 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6735
6736 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6737 ADISPLAY_ID_DEFAULT);
6738 mDispatcher->notifyMotion(&motionArgs);
6739 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6740 window->assertNoEvents();
6741}
6742
6743TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6744 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6745 std::make_shared<FakeApplicationHandle>();
6746 sp<FakeWindowHandle> obscuringWindow =
6747 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6748 ADISPLAY_ID_DEFAULT);
6749 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6750 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006751 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006752 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6753 sp<FakeWindowHandle> window =
6754 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006755 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006756 window->setOwnerInfo(222, 222);
6757 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6758 window->setFocusable(true);
6759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6760 setFocusedWindow(window);
6761 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6762
6763 // With the flag set, window should not get any input
6764 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6765 mDispatcher->notifyKey(&keyArgs);
6766 window->assertNoEvents();
6767
6768 NotifyMotionArgs motionArgs =
6769 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6770 ADISPLAY_ID_DEFAULT);
6771 mDispatcher->notifyMotion(&motionArgs);
6772 window->assertNoEvents();
6773
6774 // When the window is no longer obscured because it went on top, it should get input
6775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6776
6777 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6778 mDispatcher->notifyKey(&keyArgs);
6779 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6780
6781 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6782 ADISPLAY_ID_DEFAULT);
6783 mDispatcher->notifyMotion(&motionArgs);
6784 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6785 window->assertNoEvents();
6786}
6787
Antonio Kantekf16f2832021-09-28 04:39:20 +00006788class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6789protected:
6790 std::shared_ptr<FakeApplicationHandle> mApp;
6791 sp<FakeWindowHandle> mWindow;
6792 sp<FakeWindowHandle> mSecondWindow;
6793
6794 void SetUp() override {
6795 InputDispatcherTest::SetUp();
6796
6797 mApp = std::make_shared<FakeApplicationHandle>();
6798 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6799 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006800 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006801 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6802 mSecondWindow->setFocusable(true);
6803
6804 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006806 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006807
6808 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006809 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kanteka042c022022-07-06 16:51:07 -07006810 WINDOW_UID, true /*hasPermission*/, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006811 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6812 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6813 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006814 }
6815
Antonio Kantekea47acb2021-12-23 12:41:25 -08006816 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006817 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6818 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006819 mWindow->consumeTouchModeEvent(inTouchMode);
6820 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6821 }
6822};
6823
Antonio Kantek26defcf2022-02-08 01:12:27 +00006824TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006825 const WindowInfo& windowInfo = *mWindow->getInfo();
6826 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006827 windowInfo.ownerUid, false /*hasPermission*/);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006828}
6829
Antonio Kantek26defcf2022-02-08 01:12:27 +00006830TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6831 const WindowInfo& windowInfo = *mWindow->getInfo();
6832 int32_t ownerPid = windowInfo.ownerPid;
6833 int32_t ownerUid = windowInfo.ownerUid;
6834 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6835 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006836 ownerUid, false /*hasPermission*/,
6837 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006838 mWindow->assertNoEvents();
6839 mSecondWindow->assertNoEvents();
6840}
6841
6842TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6843 const WindowInfo& windowInfo = *mWindow->getInfo();
6844 int32_t ownerPid = windowInfo.ownerPid;
6845 int32_t ownerUid = windowInfo.ownerUid;
6846 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6847 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006848 true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006849}
6850
Antonio Kantekf16f2832021-09-28 04:39:20 +00006851TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006852 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006853 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6854 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006855 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006856 mWindow->assertNoEvents();
6857 mSecondWindow->assertNoEvents();
6858}
6859
Antonio Kantek48710e42022-03-24 14:19:30 -07006860TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6861 // Interact with the window first.
6862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6863 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6864 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6865
6866 // Then remove focus.
6867 mWindow->setFocusable(false);
6868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6869
6870 // Assert that caller can switch touch mode by owning one of the last interacted window.
6871 const WindowInfo& windowInfo = *mWindow->getInfo();
6872 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6873 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006874 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006875}
6876
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006877class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6878public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006879 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006880 std::shared_ptr<FakeApplicationHandle> application =
6881 std::make_shared<FakeApplicationHandle>();
6882 std::string name = "Fake Spy ";
6883 name += std::to_string(mSpyCount++);
6884 sp<FakeWindowHandle> spy =
6885 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006886 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006887 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006888 return spy;
6889 }
6890
6891 sp<FakeWindowHandle> createForeground() {
6892 std::shared_ptr<FakeApplicationHandle> application =
6893 std::make_shared<FakeApplicationHandle>();
6894 sp<FakeWindowHandle> window =
6895 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006896 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006897 return window;
6898 }
6899
6900private:
6901 int mSpyCount{0};
6902};
6903
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006904using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006905/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006906 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6907 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006908TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6909 ScopedSilentDeath _silentDeath;
6910
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006911 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006912 spy->setTrustedOverlay(false);
6913 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6914 ".* not a trusted overlay");
6915}
6916
6917/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006918 * Input injection into a display with a spy window but no foreground windows should succeed.
6919 */
6920TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006921 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6923
6924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6926 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6927 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6928}
6929
6930/**
6931 * Verify the order in which different input windows receive events. The touched foreground window
6932 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6933 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6934 * receive events before ones belows it.
6935 *
6936 * Here, we set up a scenario with four windows in the following Z order from the top:
6937 * spy1, spy2, window, spy3.
6938 * We then inject an event and verify that the foreground "window" receives it first, followed by
6939 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6940 * window.
6941 */
6942TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6943 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006944 auto spy1 = createSpy();
6945 auto spy2 = createSpy();
6946 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6948 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6949 const size_t numChannels = channels.size();
6950
Michael Wright8e9a8562022-02-09 13:44:29 +00006951 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006952 if (!epollFd.ok()) {
6953 FAIL() << "Failed to create epoll fd";
6954 }
6955
6956 for (size_t i = 0; i < numChannels; i++) {
6957 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6958 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6959 FAIL() << "Failed to add fd to epoll";
6960 }
6961 }
6962
6963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6964 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6965 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6966
6967 std::vector<size_t> eventOrder;
6968 std::vector<struct epoll_event> events(numChannels);
6969 for (;;) {
6970 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6971 (100ms).count());
6972 if (nFds < 0) {
6973 FAIL() << "Failed to call epoll_wait";
6974 }
6975 if (nFds == 0) {
6976 break; // epoll_wait timed out
6977 }
6978 for (int i = 0; i < nFds; i++) {
6979 ASSERT_EQ(EPOLLIN, events[i].events);
6980 eventOrder.push_back(events[i].data.u64);
6981 channels[i]->consumeMotionDown();
6982 }
6983 }
6984
6985 // Verify the order in which the events were received.
6986 EXPECT_EQ(3u, eventOrder.size());
6987 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6988 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6989 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6990}
6991
6992/**
6993 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6994 */
6995TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6996 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006997 auto spy = createSpy();
6998 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7000
7001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7002 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7003 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7004 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7005 spy->assertNoEvents();
7006}
7007
7008/**
7009 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7010 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7011 * to the window.
7012 */
7013TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7014 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007015 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007016 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7017 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7018
7019 // Inject an event outside the spy window's touchable region.
7020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7021 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7022 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7023 window->consumeMotionDown();
7024 spy->assertNoEvents();
7025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7026 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7027 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7028 window->consumeMotionUp();
7029 spy->assertNoEvents();
7030
7031 // Inject an event inside the spy window's touchable region.
7032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7033 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7034 {5, 10}))
7035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7036 window->consumeMotionDown();
7037 spy->consumeMotionDown();
7038}
7039
7040/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007041 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007042 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007043 */
7044TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7045 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007046 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007047 auto spy = createSpy();
7048 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007049 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007050 spy->setFrame(Rect{0, 0, 20, 20});
7051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7052
7053 // Inject an event outside the spy window's frame and touchable region.
7054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007055 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7056 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7058 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007059 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007060}
7061
7062/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007063 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7064 * pointers that are down within its bounds.
7065 */
7066TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7067 auto windowLeft = createForeground();
7068 windowLeft->setFrame({0, 0, 100, 200});
7069 auto windowRight = createForeground();
7070 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007071 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007072 spy->setFrame({0, 0, 200, 200});
7073 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7074
7075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7077 {50, 50}))
7078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7079 windowLeft->consumeMotionDown();
7080 spy->consumeMotionDown();
7081
7082 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007083 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007084 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7085 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7086 .pointer(
7087 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7088 .build();
7089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7090 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7091 InputEventInjectionSync::WAIT_FOR_RESULT))
7092 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7093 windowRight->consumeMotionDown();
7094 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7095}
7096
7097/**
7098 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7099 * the spy should receive the second pointer with ACTION_DOWN.
7100 */
7101TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7102 auto window = createForeground();
7103 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007104 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007105 spyRight->setFrame({100, 0, 200, 200});
7106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7107
7108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7109 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7110 {50, 50}))
7111 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7112 window->consumeMotionDown();
7113 spyRight->assertNoEvents();
7114
7115 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007116 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007117 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7118 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7119 .pointer(
7120 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7121 .build();
7122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7123 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7124 InputEventInjectionSync::WAIT_FOR_RESULT))
7125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7126 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7127 spyRight->consumeMotionDown();
7128}
7129
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007130/**
7131 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7132 * windows should be allowed to control split touch.
7133 */
7134TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007135 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007136 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007137 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007138 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007139
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007140 auto window = createForeground();
7141 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007142
7143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7144
7145 // First finger down, no window touched.
7146 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7147 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7148 {100, 200}))
7149 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7150 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7151 window->assertNoEvents();
7152
7153 // Second finger down on window, the window should receive touch down.
7154 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007155 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007156 .displayId(ADISPLAY_ID_DEFAULT)
7157 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7158 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7159 .x(100)
7160 .y(200))
7161 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7162 .build();
7163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7164 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7165 InputEventInjectionSync::WAIT_FOR_RESULT))
7166 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7167
7168 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7169 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7170}
7171
7172/**
7173 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7174 * do not receive key events.
7175 */
7176TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007177 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007178 spy->setFocusable(false);
7179
7180 auto window = createForeground();
7181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7182 setFocusedWindow(window);
7183 window->consumeFocusEvent(true);
7184
7185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7186 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7187 window->consumeKeyDown(ADISPLAY_ID_NONE);
7188
7189 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7190 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7191 window->consumeKeyUp(ADISPLAY_ID_NONE);
7192
7193 spy->assertNoEvents();
7194}
7195
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007196using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7197
7198/**
7199 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7200 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7201 */
7202TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7203 auto window = createForeground();
7204 auto spy1 = createSpy();
7205 auto spy2 = createSpy();
7206 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7207
7208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7209 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7210 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7211 window->consumeMotionDown();
7212 spy1->consumeMotionDown();
7213 spy2->consumeMotionDown();
7214
7215 // Pilfer pointers from the second spy window.
7216 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7217 spy2->assertNoEvents();
7218 spy1->consumeMotionCancel();
7219 window->consumeMotionCancel();
7220
7221 // The rest of the gesture should only be sent to the second spy window.
7222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7223 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7224 ADISPLAY_ID_DEFAULT))
7225 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7226 spy2->consumeMotionMove();
7227 spy1->assertNoEvents();
7228 window->assertNoEvents();
7229}
7230
7231/**
7232 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7233 * in the middle of the gesture.
7234 */
7235TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7236 auto window = createForeground();
7237 auto spy = createSpy();
7238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7239
7240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7241 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7242 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7243 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7244 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7245
7246 window->releaseChannel();
7247
7248 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7249
7250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7251 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7252 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7253 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7254}
7255
7256/**
7257 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7258 * the spy, but not to any other windows.
7259 */
7260TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7261 auto spy = createSpy();
7262 auto window = createForeground();
7263
7264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7265
7266 // First finger down on the window and the spy.
7267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7268 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7269 {100, 200}))
7270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7271 spy->consumeMotionDown();
7272 window->consumeMotionDown();
7273
7274 // Spy window pilfers the pointers.
7275 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7276 window->consumeMotionCancel();
7277
7278 // Second finger down on the window and spy, but the window should not receive the pointer down.
7279 const MotionEvent secondFingerDownEvent =
7280 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7281 .displayId(ADISPLAY_ID_DEFAULT)
7282 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7283 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7284 .x(100)
7285 .y(200))
7286 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7287 .build();
7288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7289 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7290 InputEventInjectionSync::WAIT_FOR_RESULT))
7291 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7292
7293 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7294
7295 // Third finger goes down outside all windows, so injection should fail.
7296 const MotionEvent thirdFingerDownEvent =
7297 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7298 .displayId(ADISPLAY_ID_DEFAULT)
7299 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7300 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7301 .x(100)
7302 .y(200))
7303 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7304 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7305 .build();
7306 ASSERT_EQ(InputEventInjectionResult::FAILED,
7307 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7308 InputEventInjectionSync::WAIT_FOR_RESULT))
7309 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7310
7311 spy->assertNoEvents();
7312 window->assertNoEvents();
7313}
7314
7315/**
7316 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7317 */
7318TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7319 auto spy = createSpy();
7320 spy->setFrame(Rect(0, 0, 100, 100));
7321 auto window = createForeground();
7322 window->setFrame(Rect(0, 0, 200, 200));
7323
7324 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7325
7326 // First finger down on the window only
7327 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7328 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7329 {150, 150}))
7330 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7331 window->consumeMotionDown();
7332
7333 // Second finger down on the spy and window
7334 const MotionEvent secondFingerDownEvent =
7335 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7336 .displayId(ADISPLAY_ID_DEFAULT)
7337 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7338 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7339 .x(150)
7340 .y(150))
7341 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7342 .build();
7343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7344 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7345 InputEventInjectionSync::WAIT_FOR_RESULT))
7346 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7347 spy->consumeMotionDown();
7348 window->consumeMotionPointerDown(1);
7349
7350 // Third finger down on the spy and window
7351 const MotionEvent thirdFingerDownEvent =
7352 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7353 .displayId(ADISPLAY_ID_DEFAULT)
7354 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7355 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7356 .x(150)
7357 .y(150))
7358 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7359 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7360 .build();
7361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7362 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7363 InputEventInjectionSync::WAIT_FOR_RESULT))
7364 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7365 spy->consumeMotionPointerDown(1);
7366 window->consumeMotionPointerDown(2);
7367
7368 // Spy window pilfers the pointers.
7369 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7370 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7371 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7372
7373 spy->assertNoEvents();
7374 window->assertNoEvents();
7375}
7376
7377/**
7378 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7379 * other windows should be canceled. If this results in the cancellation of all pointers for some
7380 * window, then that window should receive ACTION_CANCEL.
7381 */
7382TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7383 auto spy = createSpy();
7384 spy->setFrame(Rect(0, 0, 100, 100));
7385 auto window = createForeground();
7386 window->setFrame(Rect(0, 0, 200, 200));
7387
7388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7389
7390 // First finger down on both spy and window
7391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7392 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7393 {10, 10}))
7394 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7395 window->consumeMotionDown();
7396 spy->consumeMotionDown();
7397
7398 // Second finger down on the spy and window
7399 const MotionEvent secondFingerDownEvent =
7400 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7401 .displayId(ADISPLAY_ID_DEFAULT)
7402 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7403 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7404 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7405 .build();
7406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7407 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7408 InputEventInjectionSync::WAIT_FOR_RESULT))
7409 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7410 spy->consumeMotionPointerDown(1);
7411 window->consumeMotionPointerDown(1);
7412
7413 // Spy window pilfers the pointers.
7414 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7415 window->consumeMotionCancel();
7416
7417 spy->assertNoEvents();
7418 window->assertNoEvents();
7419}
7420
7421/**
7422 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7423 * be sent to other windows
7424 */
7425TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7426 auto spy = createSpy();
7427 spy->setFrame(Rect(0, 0, 100, 100));
7428 auto window = createForeground();
7429 window->setFrame(Rect(0, 0, 200, 200));
7430
7431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7432
7433 // First finger down on both window and spy
7434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7435 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7436 {10, 10}))
7437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7438 window->consumeMotionDown();
7439 spy->consumeMotionDown();
7440
7441 // Spy window pilfers the pointers.
7442 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7443 window->consumeMotionCancel();
7444
7445 // Second finger down on the window only
7446 const MotionEvent secondFingerDownEvent =
7447 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7448 .displayId(ADISPLAY_ID_DEFAULT)
7449 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7450 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7451 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7452 .x(150)
7453 .y(150))
7454 .build();
7455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7456 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7457 InputEventInjectionSync::WAIT_FOR_RESULT))
7458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7459 window->consumeMotionDown();
7460 window->assertNoEvents();
7461
7462 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7463 spy->consumeMotionMove();
7464 spy->assertNoEvents();
7465}
7466
Prabir Pradhand65552b2021-10-07 11:23:50 -07007467class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7468public:
7469 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7470 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7471 std::make_shared<FakeApplicationHandle>();
7472 sp<FakeWindowHandle> overlay =
7473 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7474 ADISPLAY_ID_DEFAULT);
7475 overlay->setFocusable(false);
7476 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007477 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007478 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007479 overlay->setTrustedOverlay(true);
7480
7481 std::shared_ptr<FakeApplicationHandle> application =
7482 std::make_shared<FakeApplicationHandle>();
7483 sp<FakeWindowHandle> window =
7484 new FakeWindowHandle(application, mDispatcher, "Application window",
7485 ADISPLAY_ID_DEFAULT);
7486 window->setFocusable(true);
7487 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007488
7489 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7491 setFocusedWindow(window);
7492 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7493 return {std::move(overlay), std::move(window)};
7494 }
7495
7496 void sendFingerEvent(int32_t action) {
7497 NotifyMotionArgs motionArgs =
7498 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7499 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7500 mDispatcher->notifyMotion(&motionArgs);
7501 }
7502
7503 void sendStylusEvent(int32_t action) {
7504 NotifyMotionArgs motionArgs =
7505 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7506 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7507 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7508 mDispatcher->notifyMotion(&motionArgs);
7509 }
7510};
7511
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007512using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7513
7514TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7515 ScopedSilentDeath _silentDeath;
7516
Prabir Pradhand65552b2021-10-07 11:23:50 -07007517 auto [overlay, window] = setupStylusOverlayScenario();
7518 overlay->setTrustedOverlay(false);
7519 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7520 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7521 ".* not a trusted overlay");
7522}
7523
7524TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7525 auto [overlay, window] = setupStylusOverlayScenario();
7526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7527
7528 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7529 overlay->consumeMotionDown();
7530 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7531 overlay->consumeMotionUp();
7532
7533 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7534 window->consumeMotionDown();
7535 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7536 window->consumeMotionUp();
7537
7538 overlay->assertNoEvents();
7539 window->assertNoEvents();
7540}
7541
7542TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7543 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007544 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7546
7547 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7548 overlay->consumeMotionDown();
7549 window->consumeMotionDown();
7550 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7551 overlay->consumeMotionUp();
7552 window->consumeMotionUp();
7553
7554 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7555 window->consumeMotionDown();
7556 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7557 window->consumeMotionUp();
7558
7559 overlay->assertNoEvents();
7560 window->assertNoEvents();
7561}
7562
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007563/**
7564 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7565 * The scenario is as follows:
7566 * - The stylus interceptor overlay is configured as a spy window.
7567 * - The stylus interceptor spy receives the start of a new stylus gesture.
7568 * - It pilfers pointers and then configures itself to no longer be a spy.
7569 * - The stylus interceptor continues to receive the rest of the gesture.
7570 */
7571TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7572 auto [overlay, window] = setupStylusOverlayScenario();
7573 overlay->setSpy(true);
7574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7575
7576 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7577 overlay->consumeMotionDown();
7578 window->consumeMotionDown();
7579
7580 // The interceptor pilfers the pointers.
7581 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7582 window->consumeMotionCancel();
7583
7584 // The interceptor configures itself so that it is no longer a spy.
7585 overlay->setSpy(false);
7586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7587
7588 // It continues to receive the rest of the stylus gesture.
7589 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7590 overlay->consumeMotionMove();
7591 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7592 overlay->consumeMotionUp();
7593
7594 window->assertNoEvents();
7595}
7596
Prabir Pradhan5735a322022-04-11 17:23:34 +00007597struct User {
7598 int32_t mPid;
7599 int32_t mUid;
7600 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7601 std::unique_ptr<InputDispatcher>& mDispatcher;
7602
7603 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7604 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7605
7606 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7607 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7608 ADISPLAY_ID_DEFAULT, {100, 200},
7609 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7610 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7611 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7612 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7613 }
7614
7615 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7616 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7617 InputEventInjectionSync::WAIT_FOR_RESULT,
7618 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7619 mPolicyFlags);
7620 }
7621
7622 sp<FakeWindowHandle> createWindow() const {
7623 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7624 std::make_shared<FakeApplicationHandle>();
7625 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7626 "Owned Window", ADISPLAY_ID_DEFAULT);
7627 window->setOwnerInfo(mPid, mUid);
7628 return window;
7629 }
7630};
7631
7632using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7633
7634TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7635 auto owner = User(mDispatcher, 10, 11);
7636 auto window = owner.createWindow();
7637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7638
7639 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7640 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7641 window->consumeMotionDown();
7642
7643 setFocusedWindow(window);
7644 window->consumeFocusEvent(true);
7645
7646 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7647 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7648 window->consumeKeyDown(ADISPLAY_ID_NONE);
7649}
7650
7651TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7652 auto owner = User(mDispatcher, 10, 11);
7653 auto window = owner.createWindow();
7654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7655
7656 auto rando = User(mDispatcher, 20, 21);
7657 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7658 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7659
7660 setFocusedWindow(window);
7661 window->consumeFocusEvent(true);
7662
7663 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7664 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7665 window->assertNoEvents();
7666}
7667
7668TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7669 auto owner = User(mDispatcher, 10, 11);
7670 auto window = owner.createWindow();
7671 auto spy = owner.createWindow();
7672 spy->setSpy(true);
7673 spy->setTrustedOverlay(true);
7674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7675
7676 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7677 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7678 spy->consumeMotionDown();
7679 window->consumeMotionDown();
7680}
7681
7682TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7683 auto owner = User(mDispatcher, 10, 11);
7684 auto window = owner.createWindow();
7685
7686 auto rando = User(mDispatcher, 20, 21);
7687 auto randosSpy = rando.createWindow();
7688 randosSpy->setSpy(true);
7689 randosSpy->setTrustedOverlay(true);
7690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7691
7692 // The event is targeted at owner's window, so injection should succeed, but the spy should
7693 // not receive the event.
7694 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7695 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7696 randosSpy->assertNoEvents();
7697 window->consumeMotionDown();
7698}
7699
7700TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7701 auto owner = User(mDispatcher, 10, 11);
7702 auto window = owner.createWindow();
7703
7704 auto rando = User(mDispatcher, 20, 21);
7705 auto randosSpy = rando.createWindow();
7706 randosSpy->setSpy(true);
7707 randosSpy->setTrustedOverlay(true);
7708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7709
7710 // A user that has injection permission can inject into any window.
7711 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7712 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7713 ADISPLAY_ID_DEFAULT));
7714 randosSpy->consumeMotionDown();
7715 window->consumeMotionDown();
7716
7717 setFocusedWindow(randosSpy);
7718 randosSpy->consumeFocusEvent(true);
7719
7720 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7721 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7722 window->assertNoEvents();
7723}
7724
7725TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7726 auto owner = User(mDispatcher, 10, 11);
7727 auto window = owner.createWindow();
7728
7729 auto rando = User(mDispatcher, 20, 21);
7730 auto randosWindow = rando.createWindow();
7731 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7732 randosWindow->setWatchOutsideTouch(true);
7733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7734
7735 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7736 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7737 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7738 window->consumeMotionDown();
7739 randosWindow->consumeMotionOutside();
7740}
7741
Garfield Tane84e6f92019-08-29 17:28:41 -07007742} // namespace android::inputdispatcher