blob: b2148eff31fea32efadf18e20ceee400bfcbb800 [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
2373/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002374 * Ensure the correct coordinate spaces are used by InputDispatcher.
2375 *
2376 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2377 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2378 * space.
2379 */
2380class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2381public:
2382 void SetUp() override {
2383 InputDispatcherTest::SetUp();
2384 mDisplayInfos.clear();
2385 mWindowInfos.clear();
2386 }
2387
2388 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2389 gui::DisplayInfo info;
2390 info.displayId = displayId;
2391 info.transform = transform;
2392 mDisplayInfos.push_back(std::move(info));
2393 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2394 }
2395
2396 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2397 mWindowInfos.push_back(*windowHandle->getInfo());
2398 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2399 }
2400
2401 // Set up a test scenario where the display has a scaled projection and there are two windows
2402 // on the display.
2403 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2404 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2405 // respectively.
2406 ui::Transform displayTransform;
2407 displayTransform.set(2, 0, 0, 4);
2408 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2409
2410 std::shared_ptr<FakeApplicationHandle> application =
2411 std::make_shared<FakeApplicationHandle>();
2412
2413 // Add two windows to the display. Their frames are represented in the display space.
2414 sp<FakeWindowHandle> firstWindow =
2415 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002416 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2417 addWindow(firstWindow);
2418
2419 sp<FakeWindowHandle> secondWindow =
2420 new FakeWindowHandle(application, mDispatcher, "Second Window",
2421 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002422 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2423 addWindow(secondWindow);
2424 return {std::move(firstWindow), std::move(secondWindow)};
2425 }
2426
2427private:
2428 std::vector<gui::DisplayInfo> mDisplayInfos;
2429 std::vector<gui::WindowInfo> mWindowInfos;
2430};
2431
2432TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2433 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2434 // Send down to the first window. The point is represented in the display space. The point is
2435 // selected so that if the hit test was done with the transform applied to it, then it would
2436 // end up in the incorrect window.
2437 NotifyMotionArgs downMotionArgs =
2438 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2439 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2440 mDispatcher->notifyMotion(&downMotionArgs);
2441
2442 firstWindow->consumeMotionDown();
2443 secondWindow->assertNoEvents();
2444}
2445
2446// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2447// the event should be treated as being in the logical display space.
2448TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2449 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2450 // Send down to the first window. The point is represented in the logical display space. The
2451 // point is selected so that if the hit test was done in logical display space, then it would
2452 // end up in the incorrect window.
2453 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2454 PointF{75 * 2, 55 * 4});
2455
2456 firstWindow->consumeMotionDown();
2457 secondWindow->assertNoEvents();
2458}
2459
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002460// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2461// event should be treated as being in the logical display space.
2462TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2463 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2464
2465 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2466 ui::Transform injectedEventTransform;
2467 injectedEventTransform.set(matrix);
2468 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2469 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2470
2471 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2472 .displayId(ADISPLAY_ID_DEFAULT)
2473 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2474 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2475 .x(untransformedPoint.x)
2476 .y(untransformedPoint.y))
2477 .build();
2478 event.transform(matrix);
2479
2480 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2481 InputEventInjectionSync::WAIT_FOR_RESULT);
2482
2483 firstWindow->consumeMotionDown();
2484 secondWindow->assertNoEvents();
2485}
2486
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002487TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2488 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2489
2490 // Send down to the second window.
2491 NotifyMotionArgs downMotionArgs =
2492 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2493 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2494 mDispatcher->notifyMotion(&downMotionArgs);
2495
2496 firstWindow->assertNoEvents();
2497 const MotionEvent* event = secondWindow->consumeMotion();
2498 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2499
2500 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2501 EXPECT_EQ(300, event->getRawX(0));
2502 EXPECT_EQ(880, event->getRawY(0));
2503
2504 // Ensure that the x and y values are in the window's coordinate space.
2505 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2506 // the logical display space. This will be the origin of the window space.
2507 EXPECT_EQ(100, event->getX(0));
2508 EXPECT_EQ(80, event->getY(0));
2509}
2510
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002511using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2512 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002513
2514class TransferTouchFixture : public InputDispatcherTest,
2515 public ::testing::WithParamInterface<TransferFunction> {};
2516
2517TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002518 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002519
2520 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002521 sp<FakeWindowHandle> firstWindow =
2522 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2523 sp<FakeWindowHandle> secondWindow =
2524 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002525
2526 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002528
2529 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002530 NotifyMotionArgs downMotionArgs =
2531 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2532 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002533 mDispatcher->notifyMotion(&downMotionArgs);
2534 // Only the first window should get the down event
2535 firstWindow->consumeMotionDown();
2536 secondWindow->assertNoEvents();
2537
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002538 // Transfer touch to the second window
2539 TransferFunction f = GetParam();
2540 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2541 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002542 // The first window gets cancel and the second gets down
2543 firstWindow->consumeMotionCancel();
2544 secondWindow->consumeMotionDown();
2545
2546 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002547 NotifyMotionArgs upMotionArgs =
2548 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2549 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002550 mDispatcher->notifyMotion(&upMotionArgs);
2551 // The first window gets no events and the second gets up
2552 firstWindow->assertNoEvents();
2553 secondWindow->consumeMotionUp();
2554}
2555
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002556/**
2557 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2558 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2559 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2560 * natural to the user.
2561 * In this test, we are sending a pointer to both spy window and first window. We then try to
2562 * transfer touch to the second window. The dispatcher should identify the first window as the
2563 * one that should lose the gesture, and therefore the action should be to move the gesture from
2564 * the first window to the second.
2565 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2566 * the other API, as well.
2567 */
2568TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2570
2571 // Create a couple of windows + a spy window
2572 sp<FakeWindowHandle> spyWindow =
2573 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2574 spyWindow->setTrustedOverlay(true);
2575 spyWindow->setSpy(true);
2576 sp<FakeWindowHandle> firstWindow =
2577 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2578 sp<FakeWindowHandle> secondWindow =
2579 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2580
2581 // Add the windows to the dispatcher
2582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2583
2584 // Send down to the first window
2585 NotifyMotionArgs downMotionArgs =
2586 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2587 ADISPLAY_ID_DEFAULT);
2588 mDispatcher->notifyMotion(&downMotionArgs);
2589 // Only the first window and spy should get the down event
2590 spyWindow->consumeMotionDown();
2591 firstWindow->consumeMotionDown();
2592
2593 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2594 // if f === 'transferTouch'.
2595 TransferFunction f = GetParam();
2596 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2597 ASSERT_TRUE(success);
2598 // The first window gets cancel and the second gets down
2599 firstWindow->consumeMotionCancel();
2600 secondWindow->consumeMotionDown();
2601
2602 // Send up event to the second window
2603 NotifyMotionArgs upMotionArgs =
2604 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2605 ADISPLAY_ID_DEFAULT);
2606 mDispatcher->notifyMotion(&upMotionArgs);
2607 // The first window gets no events and the second+spy get up
2608 firstWindow->assertNoEvents();
2609 spyWindow->consumeMotionUp();
2610 secondWindow->consumeMotionUp();
2611}
2612
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002613TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002614 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002615
2616 PointF touchPoint = {10, 10};
2617
2618 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002619 sp<FakeWindowHandle> firstWindow =
2620 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002621 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002622 sp<FakeWindowHandle> secondWindow =
2623 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002624 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002625
2626 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002628
2629 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002630 NotifyMotionArgs downMotionArgs =
2631 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2632 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002633 mDispatcher->notifyMotion(&downMotionArgs);
2634 // Only the first window should get the down event
2635 firstWindow->consumeMotionDown();
2636 secondWindow->assertNoEvents();
2637
2638 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002639 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002640 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002641 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002642 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2643 // Only the first window should get the pointer down event
2644 firstWindow->consumeMotionPointerDown(1);
2645 secondWindow->assertNoEvents();
2646
2647 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002648 TransferFunction f = GetParam();
2649 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2650 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002651 // The first window gets cancel and the second gets down and pointer down
2652 firstWindow->consumeMotionCancel();
2653 secondWindow->consumeMotionDown();
2654 secondWindow->consumeMotionPointerDown(1);
2655
2656 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002657 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002658 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002659 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002660 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2661 // The first window gets nothing and the second gets pointer up
2662 firstWindow->assertNoEvents();
2663 secondWindow->consumeMotionPointerUp(1);
2664
2665 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002666 NotifyMotionArgs upMotionArgs =
2667 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2668 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002669 mDispatcher->notifyMotion(&upMotionArgs);
2670 // The first window gets nothing and the second gets up
2671 firstWindow->assertNoEvents();
2672 secondWindow->consumeMotionUp();
2673}
2674
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002675// For the cases of single pointer touch and two pointers non-split touch, the api's
2676// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2677// for the case where there are multiple pointers split across several windows.
2678INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2679 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002680 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2681 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002682 return dispatcher->transferTouch(destChannelToken,
2683 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002684 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002685 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2686 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002687 return dispatcher->transferTouchFocus(from, to,
2688 false /*isDragAndDrop*/);
2689 }));
2690
Svet Ganov5d3bc372020-01-26 23:11:07 -08002691TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002692 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002693
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002694 sp<FakeWindowHandle> firstWindow =
2695 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002696 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002697
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002698 sp<FakeWindowHandle> secondWindow =
2699 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002700 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002701
2702 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002704
2705 PointF pointInFirst = {300, 200};
2706 PointF pointInSecond = {300, 600};
2707
2708 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002709 NotifyMotionArgs firstDownMotionArgs =
2710 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2711 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002712 mDispatcher->notifyMotion(&firstDownMotionArgs);
2713 // Only the first window should get the down event
2714 firstWindow->consumeMotionDown();
2715 secondWindow->assertNoEvents();
2716
2717 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002718 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002719 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002720 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002721 mDispatcher->notifyMotion(&secondDownMotionArgs);
2722 // The first window gets a move and the second a down
2723 firstWindow->consumeMotionMove();
2724 secondWindow->consumeMotionDown();
2725
2726 // Transfer touch focus to the second window
2727 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2728 // The first window gets cancel and the new gets pointer down (it already saw down)
2729 firstWindow->consumeMotionCancel();
2730 secondWindow->consumeMotionPointerDown(1);
2731
2732 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002733 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002734 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002735 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002736 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2737 // The first window gets nothing and the second gets pointer up
2738 firstWindow->assertNoEvents();
2739 secondWindow->consumeMotionPointerUp(1);
2740
2741 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002742 NotifyMotionArgs upMotionArgs =
2743 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2744 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002745 mDispatcher->notifyMotion(&upMotionArgs);
2746 // The first window gets nothing and the second gets up
2747 firstWindow->assertNoEvents();
2748 secondWindow->consumeMotionUp();
2749}
2750
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002751// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2752// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2753// touch is not supported, so the touch should continue on those windows and the transferred-to
2754// window should get nothing.
2755TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2756 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2757
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002758 sp<FakeWindowHandle> firstWindow =
2759 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2760 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002761
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002762 sp<FakeWindowHandle> secondWindow =
2763 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2764 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002765
2766 // Add the windows to the dispatcher
2767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2768
2769 PointF pointInFirst = {300, 200};
2770 PointF pointInSecond = {300, 600};
2771
2772 // Send down to the first window
2773 NotifyMotionArgs firstDownMotionArgs =
2774 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2775 ADISPLAY_ID_DEFAULT, {pointInFirst});
2776 mDispatcher->notifyMotion(&firstDownMotionArgs);
2777 // Only the first window should get the down event
2778 firstWindow->consumeMotionDown();
2779 secondWindow->assertNoEvents();
2780
2781 // Send down to the second window
2782 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002783 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002784 {pointInFirst, pointInSecond});
2785 mDispatcher->notifyMotion(&secondDownMotionArgs);
2786 // The first window gets a move and the second a down
2787 firstWindow->consumeMotionMove();
2788 secondWindow->consumeMotionDown();
2789
2790 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002791 const bool transferred =
2792 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002793 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2794 ASSERT_FALSE(transferred);
2795 firstWindow->assertNoEvents();
2796 secondWindow->assertNoEvents();
2797
2798 // The rest of the dispatch should proceed as normal
2799 // Send pointer up to the second window
2800 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002801 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002802 {pointInFirst, pointInSecond});
2803 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2804 // The first window gets MOVE and the second gets pointer up
2805 firstWindow->consumeMotionMove();
2806 secondWindow->consumeMotionUp();
2807
2808 // Send up event to the first window
2809 NotifyMotionArgs upMotionArgs =
2810 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2811 ADISPLAY_ID_DEFAULT);
2812 mDispatcher->notifyMotion(&upMotionArgs);
2813 // The first window gets nothing and the second gets up
2814 firstWindow->consumeMotionUp();
2815 secondWindow->assertNoEvents();
2816}
2817
Arthur Hungabbb9d82021-09-01 14:52:30 +00002818// This case will create two windows and one mirrored window on the default display and mirror
2819// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2820// the windows info of second display before default display.
2821TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2823 sp<FakeWindowHandle> firstWindowInPrimary =
2824 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2825 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002826 sp<FakeWindowHandle> secondWindowInPrimary =
2827 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2828 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002829
2830 sp<FakeWindowHandle> mirrorWindowInPrimary =
2831 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2832 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002833
2834 sp<FakeWindowHandle> firstWindowInSecondary =
2835 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2836 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002837
2838 sp<FakeWindowHandle> secondWindowInSecondary =
2839 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2840 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002841
2842 // Update window info, let it find window handle of second display first.
2843 mDispatcher->setInputWindows(
2844 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2845 {ADISPLAY_ID_DEFAULT,
2846 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2847
2848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2849 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2850 {50, 50}))
2851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2852
2853 // Window should receive motion event.
2854 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2855
2856 // Transfer touch focus
2857 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2858 secondWindowInPrimary->getToken()));
2859 // The first window gets cancel.
2860 firstWindowInPrimary->consumeMotionCancel();
2861 secondWindowInPrimary->consumeMotionDown();
2862
2863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2864 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2865 ADISPLAY_ID_DEFAULT, {150, 50}))
2866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2867 firstWindowInPrimary->assertNoEvents();
2868 secondWindowInPrimary->consumeMotionMove();
2869
2870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2871 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2872 {150, 50}))
2873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2874 firstWindowInPrimary->assertNoEvents();
2875 secondWindowInPrimary->consumeMotionUp();
2876}
2877
2878// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2879// 'transferTouch' api.
2880TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2881 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2882 sp<FakeWindowHandle> firstWindowInPrimary =
2883 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2884 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002885 sp<FakeWindowHandle> secondWindowInPrimary =
2886 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2887 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002888
2889 sp<FakeWindowHandle> mirrorWindowInPrimary =
2890 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2891 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002892
2893 sp<FakeWindowHandle> firstWindowInSecondary =
2894 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2895 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002896
2897 sp<FakeWindowHandle> secondWindowInSecondary =
2898 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2899 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002900
2901 // Update window info, let it find window handle of second display first.
2902 mDispatcher->setInputWindows(
2903 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2904 {ADISPLAY_ID_DEFAULT,
2905 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2906
2907 // Touch on second display.
2908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2909 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2910 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2911
2912 // Window should receive motion event.
2913 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2914
2915 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002916 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002917
2918 // The first window gets cancel.
2919 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2920 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2921
2922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2923 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2924 SECOND_DISPLAY_ID, {150, 50}))
2925 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2926 firstWindowInPrimary->assertNoEvents();
2927 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2928
2929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2930 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2932 firstWindowInPrimary->assertNoEvents();
2933 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2934}
2935
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002936TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002938 sp<FakeWindowHandle> window =
2939 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2940
Vishnu Nair47074b82020-08-14 11:54:47 -07002941 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002943 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002944
2945 window->consumeFocusEvent(true);
2946
2947 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2948 mDispatcher->notifyKey(&keyArgs);
2949
2950 // Window should receive key down event.
2951 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2952}
2953
2954TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002956 sp<FakeWindowHandle> window =
2957 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2958
Arthur Hung72d8dc32020-03-28 00:48:39 +00002959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002960
2961 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2962 mDispatcher->notifyKey(&keyArgs);
2963 mDispatcher->waitForIdle();
2964
2965 window->assertNoEvents();
2966}
2967
2968// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2969TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002970 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002971 sp<FakeWindowHandle> window =
2972 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2973
Arthur Hung72d8dc32020-03-28 00:48:39 +00002974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002975
2976 // Send key
2977 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2978 mDispatcher->notifyKey(&keyArgs);
2979 // Send motion
2980 NotifyMotionArgs motionArgs =
2981 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2982 ADISPLAY_ID_DEFAULT);
2983 mDispatcher->notifyMotion(&motionArgs);
2984
2985 // Window should receive only the motion event
2986 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2987 window->assertNoEvents(); // Key event or focus event will not be received
2988}
2989
arthurhungea3f4fc2020-12-21 23:18:53 +08002990TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2991 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2992
arthurhungea3f4fc2020-12-21 23:18:53 +08002993 sp<FakeWindowHandle> firstWindow =
2994 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2995 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002996
arthurhungea3f4fc2020-12-21 23:18:53 +08002997 sp<FakeWindowHandle> secondWindow =
2998 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2999 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003000
3001 // Add the windows to the dispatcher
3002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3003
3004 PointF pointInFirst = {300, 200};
3005 PointF pointInSecond = {300, 600};
3006
3007 // Send down to the first window
3008 NotifyMotionArgs firstDownMotionArgs =
3009 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3010 ADISPLAY_ID_DEFAULT, {pointInFirst});
3011 mDispatcher->notifyMotion(&firstDownMotionArgs);
3012 // Only the first window should get the down event
3013 firstWindow->consumeMotionDown();
3014 secondWindow->assertNoEvents();
3015
3016 // Send down to the second window
3017 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003018 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003019 {pointInFirst, pointInSecond});
3020 mDispatcher->notifyMotion(&secondDownMotionArgs);
3021 // The first window gets a move and the second a down
3022 firstWindow->consumeMotionMove();
3023 secondWindow->consumeMotionDown();
3024
3025 // Send pointer cancel to the second window
3026 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003027 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003028 {pointInFirst, pointInSecond});
3029 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3030 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3031 // The first window gets move and the second gets cancel.
3032 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3033 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3034
3035 // Send up event.
3036 NotifyMotionArgs upMotionArgs =
3037 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3038 ADISPLAY_ID_DEFAULT);
3039 mDispatcher->notifyMotion(&upMotionArgs);
3040 // The first window gets up and the second gets nothing.
3041 firstWindow->consumeMotionUp();
3042 secondWindow->assertNoEvents();
3043}
3044
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003045TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3046 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3047
3048 sp<FakeWindowHandle> window =
3049 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
3050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3051 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3052 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3053 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3054
3055 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3056 window->assertNoEvents();
3057 mDispatcher->waitForIdle();
3058}
3059
chaviwd1c23182019-12-20 18:44:56 -08003060class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003061public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003062 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003063 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003064 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003065 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003066 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003067 }
3068
chaviwd1c23182019-12-20 18:44:56 -08003069 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3070
3071 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3072 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3073 expectedDisplayId, expectedFlags);
3074 }
3075
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003076 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3077
3078 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3079
chaviwd1c23182019-12-20 18:44:56 -08003080 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3081 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3082 expectedDisplayId, expectedFlags);
3083 }
3084
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003085 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3086 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3087 expectedDisplayId, expectedFlags);
3088 }
3089
chaviwd1c23182019-12-20 18:44:56 -08003090 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3091 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3092 expectedDisplayId, expectedFlags);
3093 }
3094
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003095 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3096 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3097 expectedDisplayId, expectedFlags);
3098 }
3099
Arthur Hungfbfa5722021-11-16 02:45:54 +00003100 void consumeMotionPointerDown(int32_t pointerIdx) {
3101 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3102 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3103 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3104 0 /*expectedFlags*/);
3105 }
3106
Evan Rosky84f07f02021-04-16 10:42:42 -07003107 MotionEvent* consumeMotion() {
3108 InputEvent* event = mInputReceiver->consume();
3109 if (!event) {
3110 ADD_FAILURE() << "No event was produced";
3111 return nullptr;
3112 }
3113 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3114 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3115 return nullptr;
3116 }
3117 return static_cast<MotionEvent*>(event);
3118 }
3119
chaviwd1c23182019-12-20 18:44:56 -08003120 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3121
3122private:
3123 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003124};
3125
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003126using InputDispatcherMonitorTest = InputDispatcherTest;
3127
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003128/**
3129 * Two entities that receive touch: A window, and a global monitor.
3130 * The touch goes to the window, and then the window disappears.
3131 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3132 * for the monitor, as well.
3133 * 1. foregroundWindow
3134 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3135 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003136TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003137 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3138 sp<FakeWindowHandle> window =
3139 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3140
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003141 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003142
3143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3145 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3146 {100, 200}))
3147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3148
3149 // Both the foreground window and the global monitor should receive the touch down
3150 window->consumeMotionDown();
3151 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3152
3153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3154 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3155 ADISPLAY_ID_DEFAULT, {110, 200}))
3156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3157
3158 window->consumeMotionMove();
3159 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3160
3161 // Now the foreground window goes away
3162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3163 window->consumeMotionCancel();
3164 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3165
3166 // If more events come in, there will be no more foreground window to send them to. This will
3167 // cause a cancel for the monitor, as well.
3168 ASSERT_EQ(InputEventInjectionResult::FAILED,
3169 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3170 ADISPLAY_ID_DEFAULT, {120, 200}))
3171 << "Injection should fail because the window was removed";
3172 window->assertNoEvents();
3173 // Global monitor now gets the cancel
3174 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3175}
3176
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003177TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003178 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003179 sp<FakeWindowHandle> window =
3180 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003182
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003183 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003184
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003186 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003187 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003188 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003189 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003190}
3191
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003192TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3193 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003194
Chris Yea209fde2020-07-22 13:54:51 -07003195 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003196 sp<FakeWindowHandle> window =
3197 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003199
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003202 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003203 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003204 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003205
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003206 // Pilfer pointers from the monitor.
3207 // This should not do anything and the window should continue to receive events.
3208 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003209
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003211 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3212 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003213 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003214
3215 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3216 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003217}
3218
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003219TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003220 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3221 sp<FakeWindowHandle> window =
3222 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3224 window->setWindowOffset(20, 40);
3225 window->setWindowTransform(0, 1, -1, 0);
3226
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003227 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003228
3229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3230 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3231 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3232 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3233 MotionEvent* event = monitor.consumeMotion();
3234 // Even though window has transform, gesture monitor must not.
3235 ASSERT_EQ(ui::Transform(), event->getTransform());
3236}
3237
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003238TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003239 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003240 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003241
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003242 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003243 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003244 << "Injection should fail if there is a monitor, but no touchable window";
3245 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003246}
3247
chaviw81e2bb92019-12-18 15:03:51 -08003248TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003249 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003250 sp<FakeWindowHandle> window =
3251 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3252
Arthur Hung72d8dc32020-03-28 00:48:39 +00003253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003254
3255 NotifyMotionArgs motionArgs =
3256 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3257 ADISPLAY_ID_DEFAULT);
3258
3259 mDispatcher->notifyMotion(&motionArgs);
3260 // Window should receive motion down event.
3261 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3262
3263 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003264 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003265 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3266 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3267 motionArgs.pointerCoords[0].getX() - 10);
3268
3269 mDispatcher->notifyMotion(&motionArgs);
3270 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3271 0 /*expectedFlags*/);
3272}
3273
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003274/**
3275 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3276 * the device default right away. In the test scenario, we check both the default value,
3277 * and the action of enabling / disabling.
3278 */
3279TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003280 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003281 sp<FakeWindowHandle> window =
3282 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003283 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003284
3285 // Set focused application.
3286 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003287 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003288
3289 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003291 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003292 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3293
3294 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003295 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003297 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3298
3299 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003300 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003301 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003302 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003303 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003305 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003306 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3307
3308 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003309 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003311 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3312
3313 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003314 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003315 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003316 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003317 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003319 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003320 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3321
3322 window->assertNoEvents();
3323}
3324
Gang Wange9087892020-01-07 12:17:14 -05003325TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003326 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003327 sp<FakeWindowHandle> window =
3328 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3329
3330 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003331 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003332
Arthur Hung72d8dc32020-03-28 00:48:39 +00003333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003334 setFocusedWindow(window);
3335
Gang Wange9087892020-01-07 12:17:14 -05003336 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3337
3338 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3339 mDispatcher->notifyKey(&keyArgs);
3340
3341 InputEvent* event = window->consume();
3342 ASSERT_NE(event, nullptr);
3343
3344 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3345 ASSERT_NE(verified, nullptr);
3346 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3347
3348 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3349 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3350 ASSERT_EQ(keyArgs.source, verified->source);
3351 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3352
3353 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3354
3355 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003356 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003357 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003358 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3359 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3360 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3361 ASSERT_EQ(0, verifiedKey.repeatCount);
3362}
3363
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003364TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003365 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003366 sp<FakeWindowHandle> window =
3367 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3368
3369 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3370
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003371 ui::Transform transform;
3372 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3373
3374 gui::DisplayInfo displayInfo;
3375 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3376 displayInfo.transform = transform;
3377
3378 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003379
3380 NotifyMotionArgs motionArgs =
3381 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3382 ADISPLAY_ID_DEFAULT);
3383 mDispatcher->notifyMotion(&motionArgs);
3384
3385 InputEvent* event = window->consume();
3386 ASSERT_NE(event, nullptr);
3387
3388 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3389 ASSERT_NE(verified, nullptr);
3390 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3391
3392 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3393 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3394 EXPECT_EQ(motionArgs.source, verified->source);
3395 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3396
3397 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3398
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003399 const vec2 rawXY =
3400 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3401 motionArgs.pointerCoords[0].getXYValue());
3402 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3403 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003404 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003405 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003406 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003407 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3408 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3409}
3410
chaviw09c8d2d2020-08-24 15:48:26 -07003411/**
3412 * Ensure that separate calls to sign the same data are generating the same key.
3413 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3414 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3415 * tests.
3416 */
3417TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3418 KeyEvent event = getTestKeyEvent();
3419 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3420
3421 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3422 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3423 ASSERT_EQ(hmac1, hmac2);
3424}
3425
3426/**
3427 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3428 */
3429TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3430 KeyEvent event = getTestKeyEvent();
3431 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3432 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3433
3434 verifiedEvent.deviceId += 1;
3435 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3436
3437 verifiedEvent.source += 1;
3438 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3439
3440 verifiedEvent.eventTimeNanos += 1;
3441 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3442
3443 verifiedEvent.displayId += 1;
3444 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3445
3446 verifiedEvent.action += 1;
3447 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3448
3449 verifiedEvent.downTimeNanos += 1;
3450 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3451
3452 verifiedEvent.flags += 1;
3453 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3454
3455 verifiedEvent.keyCode += 1;
3456 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3457
3458 verifiedEvent.scanCode += 1;
3459 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3460
3461 verifiedEvent.metaState += 1;
3462 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3463
3464 verifiedEvent.repeatCount += 1;
3465 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3466}
3467
Vishnu Nair958da932020-08-21 17:12:37 -07003468TEST_F(InputDispatcherTest, SetFocusedWindow) {
3469 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3470 sp<FakeWindowHandle> windowTop =
3471 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3472 sp<FakeWindowHandle> windowSecond =
3473 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3474 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3475
3476 // Top window is also focusable but is not granted focus.
3477 windowTop->setFocusable(true);
3478 windowSecond->setFocusable(true);
3479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3480 setFocusedWindow(windowSecond);
3481
3482 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3484 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003485
3486 // Focused window should receive event.
3487 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3488 windowTop->assertNoEvents();
3489}
3490
3491TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3492 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3493 sp<FakeWindowHandle> window =
3494 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3495 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3496
3497 window->setFocusable(true);
3498 // Release channel for window is no longer valid.
3499 window->releaseChannel();
3500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3501 setFocusedWindow(window);
3502
3503 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003504 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3505 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003506
3507 // window channel is invalid, so it should not receive any input event.
3508 window->assertNoEvents();
3509}
3510
3511TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3512 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3513 sp<FakeWindowHandle> window =
3514 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003515 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003516 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3517
Vishnu Nair958da932020-08-21 17:12:37 -07003518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3519 setFocusedWindow(window);
3520
3521 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003522 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3523 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003524
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003525 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003526 window->assertNoEvents();
3527}
3528
3529TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3530 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3531 sp<FakeWindowHandle> windowTop =
3532 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3533 sp<FakeWindowHandle> windowSecond =
3534 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3535 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3536
3537 windowTop->setFocusable(true);
3538 windowSecond->setFocusable(true);
3539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3540 setFocusedWindow(windowTop);
3541 windowTop->consumeFocusEvent(true);
3542
3543 setFocusedWindow(windowSecond, windowTop);
3544 windowSecond->consumeFocusEvent(true);
3545 windowTop->consumeFocusEvent(false);
3546
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3548 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003549
3550 // Focused window should receive event.
3551 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3552}
3553
3554TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3555 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3556 sp<FakeWindowHandle> windowTop =
3557 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3558 sp<FakeWindowHandle> windowSecond =
3559 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3560 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3561
3562 windowTop->setFocusable(true);
3563 windowSecond->setFocusable(true);
3564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3565 setFocusedWindow(windowSecond, windowTop);
3566
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003567 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3568 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003569
3570 // Event should be dropped.
3571 windowTop->assertNoEvents();
3572 windowSecond->assertNoEvents();
3573}
3574
3575TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3577 sp<FakeWindowHandle> window =
3578 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3579 sp<FakeWindowHandle> previousFocusedWindow =
3580 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3581 ADISPLAY_ID_DEFAULT);
3582 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3583
3584 window->setFocusable(true);
3585 previousFocusedWindow->setFocusable(true);
3586 window->setVisible(false);
3587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3588 setFocusedWindow(previousFocusedWindow);
3589 previousFocusedWindow->consumeFocusEvent(true);
3590
3591 // Requesting focus on invisible window takes focus from currently focused window.
3592 setFocusedWindow(window);
3593 previousFocusedWindow->consumeFocusEvent(false);
3594
3595 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003597 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003598 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003599
3600 // Window does not get focus event or key down.
3601 window->assertNoEvents();
3602
3603 // Window becomes visible.
3604 window->setVisible(true);
3605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3606
3607 // Window receives focus event.
3608 window->consumeFocusEvent(true);
3609 // Focused window receives key down.
3610 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3611}
3612
Vishnu Nair599f1412021-06-21 10:39:58 -07003613TEST_F(InputDispatcherTest, DisplayRemoved) {
3614 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3615 sp<FakeWindowHandle> window =
3616 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3617 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3618
3619 // window is granted focus.
3620 window->setFocusable(true);
3621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3622 setFocusedWindow(window);
3623 window->consumeFocusEvent(true);
3624
3625 // When a display is removed window loses focus.
3626 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3627 window->consumeFocusEvent(false);
3628}
3629
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003630/**
3631 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3632 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3633 * of the 'slipperyEnterWindow'.
3634 *
3635 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3636 * a way so that the touched location is no longer covered by the top window.
3637 *
3638 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3639 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3640 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3641 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3642 * with ACTION_DOWN).
3643 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3644 * window moved itself away from the touched location and had Flag::SLIPPERY.
3645 *
3646 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3647 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3648 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3649 *
3650 * In this test, we ensure that the event received by the bottom window has
3651 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3652 */
3653TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003654 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3655 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003656
3657 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3658 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3659
3660 sp<FakeWindowHandle> slipperyExitWindow =
3661 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003662 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003663 // Make sure this one overlaps the bottom window
3664 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3665 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3666 // one. Windows with the same owner are not considered to be occluding each other.
3667 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3668
3669 sp<FakeWindowHandle> slipperyEnterWindow =
3670 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3671 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3672
3673 mDispatcher->setInputWindows(
3674 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3675
3676 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3677 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3678 ADISPLAY_ID_DEFAULT, {{50, 50}});
3679 mDispatcher->notifyMotion(&args);
3680 slipperyExitWindow->consumeMotionDown();
3681 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3682 mDispatcher->setInputWindows(
3683 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3684
3685 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3686 ADISPLAY_ID_DEFAULT, {{51, 51}});
3687 mDispatcher->notifyMotion(&args);
3688
3689 slipperyExitWindow->consumeMotionCancel();
3690
3691 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3692 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3693}
3694
Garfield Tan1c7bc862020-01-28 13:24:04 -08003695class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3696protected:
3697 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3698 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3699
Chris Yea209fde2020-07-22 13:54:51 -07003700 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003701 sp<FakeWindowHandle> mWindow;
3702
3703 virtual void SetUp() override {
3704 mFakePolicy = new FakeInputDispatcherPolicy();
3705 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003706 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003707 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3708 ASSERT_EQ(OK, mDispatcher->start());
3709
3710 setUpWindow();
3711 }
3712
3713 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003714 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003715 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3716
Vishnu Nair47074b82020-08-14 11:54:47 -07003717 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003719 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003720 mWindow->consumeFocusEvent(true);
3721 }
3722
Chris Ye2ad95392020-09-01 13:44:44 -07003723 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003724 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003725 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003726 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3727 mDispatcher->notifyKey(&keyArgs);
3728
3729 // Window should receive key down event.
3730 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3731 }
3732
3733 void expectKeyRepeatOnce(int32_t repeatCount) {
3734 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3735 InputEvent* repeatEvent = mWindow->consume();
3736 ASSERT_NE(nullptr, repeatEvent);
3737
3738 uint32_t eventType = repeatEvent->getType();
3739 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3740
3741 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3742 uint32_t eventAction = repeatKeyEvent->getAction();
3743 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3744 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3745 }
3746
Chris Ye2ad95392020-09-01 13:44:44 -07003747 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003748 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003749 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003750 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3751 mDispatcher->notifyKey(&keyArgs);
3752
3753 // Window should receive key down event.
3754 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3755 0 /*expectedFlags*/);
3756 }
3757};
3758
3759TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003760 sendAndConsumeKeyDown(1 /* deviceId */);
3761 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3762 expectKeyRepeatOnce(repeatCount);
3763 }
3764}
3765
3766TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3767 sendAndConsumeKeyDown(1 /* deviceId */);
3768 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3769 expectKeyRepeatOnce(repeatCount);
3770 }
3771 sendAndConsumeKeyDown(2 /* deviceId */);
3772 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003773 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3774 expectKeyRepeatOnce(repeatCount);
3775 }
3776}
3777
3778TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003779 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003780 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003781 sendAndConsumeKeyUp(1 /* deviceId */);
3782 mWindow->assertNoEvents();
3783}
3784
3785TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3786 sendAndConsumeKeyDown(1 /* deviceId */);
3787 expectKeyRepeatOnce(1 /*repeatCount*/);
3788 sendAndConsumeKeyDown(2 /* deviceId */);
3789 expectKeyRepeatOnce(1 /*repeatCount*/);
3790 // Stale key up from device 1.
3791 sendAndConsumeKeyUp(1 /* deviceId */);
3792 // Device 2 is still down, keep repeating
3793 expectKeyRepeatOnce(2 /*repeatCount*/);
3794 expectKeyRepeatOnce(3 /*repeatCount*/);
3795 // Device 2 key up
3796 sendAndConsumeKeyUp(2 /* deviceId */);
3797 mWindow->assertNoEvents();
3798}
3799
3800TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3801 sendAndConsumeKeyDown(1 /* deviceId */);
3802 expectKeyRepeatOnce(1 /*repeatCount*/);
3803 sendAndConsumeKeyDown(2 /* deviceId */);
3804 expectKeyRepeatOnce(1 /*repeatCount*/);
3805 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3806 sendAndConsumeKeyUp(2 /* deviceId */);
3807 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003808 mWindow->assertNoEvents();
3809}
3810
liushenxiang42232912021-05-21 20:24:09 +08003811TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3812 sendAndConsumeKeyDown(DEVICE_ID);
3813 expectKeyRepeatOnce(1 /*repeatCount*/);
3814 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3815 mDispatcher->notifyDeviceReset(&args);
3816 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3817 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3818 mWindow->assertNoEvents();
3819}
3820
Garfield Tan1c7bc862020-01-28 13:24:04 -08003821TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003822 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003823 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3824 InputEvent* repeatEvent = mWindow->consume();
3825 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3826 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3827 IdGenerator::getSource(repeatEvent->getId()));
3828 }
3829}
3830
3831TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003832 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003833
3834 std::unordered_set<int32_t> idSet;
3835 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3836 InputEvent* repeatEvent = mWindow->consume();
3837 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3838 int32_t id = repeatEvent->getId();
3839 EXPECT_EQ(idSet.end(), idSet.find(id));
3840 idSet.insert(id);
3841 }
3842}
3843
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003844/* Test InputDispatcher for MultiDisplay */
3845class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3846public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003847 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003848 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003849
Chris Yea209fde2020-07-22 13:54:51 -07003850 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003851 windowInPrimary =
3852 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003853
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003854 // Set focus window for primary display, but focused display would be second one.
3855 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003856 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003858 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003859 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003860
Chris Yea209fde2020-07-22 13:54:51 -07003861 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003862 windowInSecondary =
3863 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003864 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003865 // Set focus display to second one.
3866 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3867 // Set focus window for second display.
3868 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003869 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003870 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003871 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003872 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003873 }
3874
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003875 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003876 InputDispatcherTest::TearDown();
3877
Chris Yea209fde2020-07-22 13:54:51 -07003878 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003879 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003880 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003881 windowInSecondary.clear();
3882 }
3883
3884protected:
Chris Yea209fde2020-07-22 13:54:51 -07003885 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003886 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003887 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003888 sp<FakeWindowHandle> windowInSecondary;
3889};
3890
3891TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3892 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003896 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003897 windowInSecondary->assertNoEvents();
3898
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003899 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003903 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003904 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003905}
3906
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003907TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003908 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3910 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003911 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003912 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003913 windowInSecondary->assertNoEvents();
3914
3915 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003917 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003918 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003919 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003920
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003921 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003922 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003923
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003924 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003925 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3926 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003927
3928 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003929 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003930 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003931 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003932 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003933 windowInSecondary->assertNoEvents();
3934}
3935
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003936// Test per-display input monitors for motion event.
3937TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003938 FakeMonitorReceiver monitorInPrimary =
3939 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3940 FakeMonitorReceiver monitorInSecondary =
3941 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003942
3943 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003947 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003948 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003949 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003950 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003951
3952 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3954 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003956 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003957 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003958 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003959 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003960
3961 // Test inject a non-pointer motion event.
3962 // If specific a display, it will dispatch to the focused window of particular display,
3963 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003964 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3965 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003967 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003968 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003969 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003970 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003971}
3972
3973// Test per-display input monitors for key event.
3974TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003975 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003976 FakeMonitorReceiver monitorInPrimary =
3977 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3978 FakeMonitorReceiver monitorInSecondary =
3979 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003980
3981 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3983 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003984 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003985 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003986 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003987 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003988}
3989
Vishnu Nair958da932020-08-21 17:12:37 -07003990TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3991 sp<FakeWindowHandle> secondWindowInPrimary =
3992 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3993 secondWindowInPrimary->setFocusable(true);
3994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3995 setFocusedWindow(secondWindowInPrimary);
3996 windowInPrimary->consumeFocusEvent(false);
3997 secondWindowInPrimary->consumeFocusEvent(true);
3998
3999 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4001 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004002 windowInPrimary->assertNoEvents();
4003 windowInSecondary->assertNoEvents();
4004 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4005}
4006
Arthur Hungdfd528e2021-12-08 13:23:04 +00004007TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4008 FakeMonitorReceiver monitorInPrimary =
4009 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4010 FakeMonitorReceiver monitorInSecondary =
4011 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4012
4013 // Test touch down on primary display.
4014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4017 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4018 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4019
4020 // Test touch down on second display.
4021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4022 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4023 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4024 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4025 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4026
4027 // Trigger cancel touch.
4028 mDispatcher->cancelCurrentTouch();
4029 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4030 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4031 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4032 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4033
4034 // Test inject a move motion event, no window/monitor should receive the event.
4035 ASSERT_EQ(InputEventInjectionResult::FAILED,
4036 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4037 ADISPLAY_ID_DEFAULT, {110, 200}))
4038 << "Inject motion event should return InputEventInjectionResult::FAILED";
4039 windowInPrimary->assertNoEvents();
4040 monitorInPrimary.assertNoEvents();
4041
4042 ASSERT_EQ(InputEventInjectionResult::FAILED,
4043 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4044 SECOND_DISPLAY_ID, {110, 200}))
4045 << "Inject motion event should return InputEventInjectionResult::FAILED";
4046 windowInSecondary->assertNoEvents();
4047 monitorInSecondary.assertNoEvents();
4048}
4049
Jackal Guof9696682018-10-05 12:23:23 +08004050class InputFilterTest : public InputDispatcherTest {
4051protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004052 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4053 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004054 NotifyMotionArgs motionArgs;
4055
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004056 motionArgs =
4057 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004058 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004059 motionArgs =
4060 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004061 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004062 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004063 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004064 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4065 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004066 } else {
4067 mFakePolicy->assertFilterInputEventWasNotCalled();
4068 }
4069 }
4070
4071 void testNotifyKey(bool expectToBeFiltered) {
4072 NotifyKeyArgs keyArgs;
4073
4074 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4075 mDispatcher->notifyKey(&keyArgs);
4076 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4077 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004078 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004079
4080 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004081 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004082 } else {
4083 mFakePolicy->assertFilterInputEventWasNotCalled();
4084 }
4085 }
4086};
4087
4088// Test InputFilter for MotionEvent
4089TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4090 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4091 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4092 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4093
4094 // Enable InputFilter
4095 mDispatcher->setInputFilterEnabled(true);
4096 // Test touch on both primary and second display, and check if both events are filtered.
4097 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4098 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4099
4100 // Disable InputFilter
4101 mDispatcher->setInputFilterEnabled(false);
4102 // Test touch on both primary and second display, and check if both events aren't filtered.
4103 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4104 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4105}
4106
4107// Test InputFilter for KeyEvent
4108TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4109 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4110 testNotifyKey(/*expectToBeFiltered*/ false);
4111
4112 // Enable InputFilter
4113 mDispatcher->setInputFilterEnabled(true);
4114 // Send a key event, and check if it is filtered.
4115 testNotifyKey(/*expectToBeFiltered*/ true);
4116
4117 // Disable InputFilter
4118 mDispatcher->setInputFilterEnabled(false);
4119 // Send a key event, and check if it isn't filtered.
4120 testNotifyKey(/*expectToBeFiltered*/ false);
4121}
4122
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004123// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4124// logical display coordinate space.
4125TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4126 ui::Transform firstDisplayTransform;
4127 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4128 ui::Transform secondDisplayTransform;
4129 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4130
4131 std::vector<gui::DisplayInfo> displayInfos(2);
4132 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4133 displayInfos[0].transform = firstDisplayTransform;
4134 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4135 displayInfos[1].transform = secondDisplayTransform;
4136
4137 mDispatcher->onWindowInfosChanged({}, displayInfos);
4138
4139 // Enable InputFilter
4140 mDispatcher->setInputFilterEnabled(true);
4141
4142 // Ensure the correct transforms are used for the displays.
4143 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4144 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4145}
4146
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004147class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4148protected:
4149 virtual void SetUp() override {
4150 InputDispatcherTest::SetUp();
4151
4152 /**
4153 * We don't need to enable input filter to test the injected event policy, but we enabled it
4154 * here to make the tests more realistic, since this policy only matters when inputfilter is
4155 * on.
4156 */
4157 mDispatcher->setInputFilterEnabled(true);
4158
4159 std::shared_ptr<InputApplicationHandle> application =
4160 std::make_shared<FakeApplicationHandle>();
4161 mWindow =
4162 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4163
4164 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4165 mWindow->setFocusable(true);
4166 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4167 setFocusedWindow(mWindow);
4168 mWindow->consumeFocusEvent(true);
4169 }
4170
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004171 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4172 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004173 KeyEvent event;
4174
4175 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4176 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4177 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4178 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4179 const int32_t additionalPolicyFlags =
4180 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004182 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4184 policyFlags | additionalPolicyFlags));
4185
4186 InputEvent* received = mWindow->consume();
4187 ASSERT_NE(nullptr, received);
4188 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004189 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4190 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4191 ASSERT_EQ(flags, keyEvent.getFlags());
4192 }
4193
4194 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4195 int32_t flags) {
4196 MotionEvent event;
4197 PointerProperties pointerProperties[1];
4198 PointerCoords pointerCoords[1];
4199 pointerProperties[0].clear();
4200 pointerProperties[0].id = 0;
4201 pointerCoords[0].clear();
4202 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4203 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4204
4205 ui::Transform identityTransform;
4206 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4207 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4208 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4209 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4210 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004211 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004212 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004213 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4214
4215 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4216 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004217 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004218 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4219 policyFlags | additionalPolicyFlags));
4220
4221 InputEvent* received = mWindow->consume();
4222 ASSERT_NE(nullptr, received);
4223 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4224 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4225 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4226 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 }
4228
4229private:
4230 sp<FakeWindowHandle> mWindow;
4231};
4232
4233TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004234 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4235 // filter. Without it, the event will no different from a regularly injected event, and the
4236 // injected device id will be overwritten.
4237 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4238 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239}
4240
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004243 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4244 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4245}
4246
4247TEST_F(InputFilterInjectionPolicyTest,
4248 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4249 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4250 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4251 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004252}
4253
4254TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4255 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004257}
4258
chaviwfd6d3512019-03-25 13:23:49 -07004259class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004260 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004261 InputDispatcherTest::SetUp();
4262
Chris Yea209fde2020-07-22 13:54:51 -07004263 std::shared_ptr<FakeApplicationHandle> application =
4264 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004265 mUnfocusedWindow =
4266 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004267 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004268
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004269 mFocusedWindow =
4270 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4271 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004272
4273 // Set focused application.
4274 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004275 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004276
4277 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004279 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004280 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004281 }
4282
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004283 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004284 InputDispatcherTest::TearDown();
4285
4286 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004287 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004288 }
4289
4290protected:
4291 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004292 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004293 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004294};
4295
4296// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4297// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4298// the onPointerDownOutsideFocus callback.
4299TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004301 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4302 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004303 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004304 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004305
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004306 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004307 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4308}
4309
4310// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4311// DOWN on the window that doesn't have focus. Ensure no window received the
4312// onPointerDownOutsideFocus callback.
4313TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004315 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004316 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004317 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004318
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004319 ASSERT_TRUE(mDispatcher->waitForIdle());
4320 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004321}
4322
4323// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4324// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4325TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4327 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004328 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004329 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004330
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004331 ASSERT_TRUE(mDispatcher->waitForIdle());
4332 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004333}
4334
4335// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4336// DOWN on the window that already has focus. Ensure no window received the
4337// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004338TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004340 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004341 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004343 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004344
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004345 ASSERT_TRUE(mDispatcher->waitForIdle());
4346 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004347}
4348
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004349// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4350// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4351TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4352 const MotionEvent event =
4353 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4354 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4355 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4356 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4357 .build();
4358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4359 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4360 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4361
4362 ASSERT_TRUE(mDispatcher->waitForIdle());
4363 mFakePolicy->assertOnPointerDownWasNotCalled();
4364 // Ensure that the unfocused window did not receive any FOCUS events.
4365 mUnfocusedWindow->assertNoEvents();
4366}
4367
chaviwaf87b3e2019-10-01 16:59:28 -07004368// These tests ensures we can send touch events to a single client when there are multiple input
4369// windows that point to the same client token.
4370class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4371 virtual void SetUp() override {
4372 InputDispatcherTest::SetUp();
4373
Chris Yea209fde2020-07-22 13:54:51 -07004374 std::shared_ptr<FakeApplicationHandle> application =
4375 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004376 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4377 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004378 mWindow1->setFrame(Rect(0, 0, 100, 100));
4379
4380 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4381 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004382 mWindow2->setFrame(Rect(100, 100, 200, 200));
4383
Arthur Hung72d8dc32020-03-28 00:48:39 +00004384 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004385 }
4386
4387protected:
4388 sp<FakeWindowHandle> mWindow1;
4389 sp<FakeWindowHandle> mWindow2;
4390
4391 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004392 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004393 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4394 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004395 }
4396
4397 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4398 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004399 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004400 InputEvent* event = window->consume();
4401
4402 ASSERT_NE(nullptr, event) << name.c_str()
4403 << ": consumer should have returned non-NULL event.";
4404
4405 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4406 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4407 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4408
4409 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004410 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004411
4412 for (size_t i = 0; i < points.size(); i++) {
4413 float expectedX = points[i].x;
4414 float expectedY = points[i].y;
4415
4416 EXPECT_EQ(expectedX, motionEvent.getX(i))
4417 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4418 << ", got " << motionEvent.getX(i);
4419 EXPECT_EQ(expectedY, motionEvent.getY(i))
4420 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4421 << ", got " << motionEvent.getY(i);
4422 }
4423 }
chaviw9eaa22c2020-07-01 16:21:27 -07004424
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004425 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004426 std::vector<PointF> expectedPoints) {
4427 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4428 ADISPLAY_ID_DEFAULT, touchedPoints);
4429 mDispatcher->notifyMotion(&motionArgs);
4430
4431 // Always consume from window1 since it's the window that has the InputReceiver
4432 consumeMotionEvent(mWindow1, action, expectedPoints);
4433 }
chaviwaf87b3e2019-10-01 16:59:28 -07004434};
4435
4436TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4437 // Touch Window 1
4438 PointF touchedPoint = {10, 10};
4439 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004440 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004441
4442 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004443 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004444
4445 // Touch Window 2
4446 touchedPoint = {150, 150};
4447 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004448 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004449}
4450
chaviw9eaa22c2020-07-01 16:21:27 -07004451TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4452 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004453 mWindow2->setWindowScale(0.5f, 0.5f);
4454
4455 // Touch Window 1
4456 PointF touchedPoint = {10, 10};
4457 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004458 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004459 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004460 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004461
4462 // Touch Window 2
4463 touchedPoint = {150, 150};
4464 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004465 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4466 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004467
chaviw9eaa22c2020-07-01 16:21:27 -07004468 // Update the transform so rotation is set
4469 mWindow2->setWindowTransform(0, -1, 1, 0);
4470 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4471 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004472}
4473
chaviw9eaa22c2020-07-01 16:21:27 -07004474TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004475 mWindow2->setWindowScale(0.5f, 0.5f);
4476
4477 // Touch Window 1
4478 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4479 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004480 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004481
4482 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004483 touchedPoints.push_back(PointF{150, 150});
4484 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004485 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004486
chaviw9eaa22c2020-07-01 16:21:27 -07004487 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004488 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004489 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004490
chaviw9eaa22c2020-07-01 16:21:27 -07004491 // Update the transform so rotation is set for Window 2
4492 mWindow2->setWindowTransform(0, -1, 1, 0);
4493 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004494 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004495}
4496
chaviw9eaa22c2020-07-01 16:21:27 -07004497TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004498 mWindow2->setWindowScale(0.5f, 0.5f);
4499
4500 // Touch Window 1
4501 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4502 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004503 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004504
4505 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004506 touchedPoints.push_back(PointF{150, 150});
4507 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004508
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004509 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004510
4511 // Move both windows
4512 touchedPoints = {{20, 20}, {175, 175}};
4513 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4514 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4515
chaviw9eaa22c2020-07-01 16:21:27 -07004516 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004517
chaviw9eaa22c2020-07-01 16:21:27 -07004518 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004519 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004520 expectedPoints.pop_back();
4521
4522 // Touch Window 2
4523 mWindow2->setWindowTransform(0, -1, 1, 0);
4524 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004525 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004526
4527 // Move both windows
4528 touchedPoints = {{20, 20}, {175, 175}};
4529 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4530 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4531
4532 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004533}
4534
4535TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4536 mWindow1->setWindowScale(0.5f, 0.5f);
4537
4538 // Touch Window 1
4539 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4540 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004541 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004542
4543 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004544 touchedPoints.push_back(PointF{150, 150});
4545 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004546
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004547 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004548
4549 // Move both windows
4550 touchedPoints = {{20, 20}, {175, 175}};
4551 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4552 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4553
chaviw9eaa22c2020-07-01 16:21:27 -07004554 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004555}
4556
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004557class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4558 virtual void SetUp() override {
4559 InputDispatcherTest::SetUp();
4560
Chris Yea209fde2020-07-22 13:54:51 -07004561 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004562 mApplication->setDispatchingTimeout(20ms);
4563 mWindow =
4564 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4565 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004566 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004567 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004568
4569 // Set focused application.
4570 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4571
4572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004573 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004574 mWindow->consumeFocusEvent(true);
4575 }
4576
4577 virtual void TearDown() override {
4578 InputDispatcherTest::TearDown();
4579 mWindow.clear();
4580 }
4581
4582protected:
Chris Yea209fde2020-07-22 13:54:51 -07004583 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004584 sp<FakeWindowHandle> mWindow;
4585 static constexpr PointF WINDOW_LOCATION = {20, 20};
4586
4587 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004589 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4590 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004592 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4593 WINDOW_LOCATION));
4594 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004595
4596 sp<FakeWindowHandle> addSpyWindow() {
4597 sp<FakeWindowHandle> spy =
4598 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4599 spy->setTrustedOverlay(true);
4600 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004601 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004602 spy->setDispatchingTimeout(30ms);
4603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4604 return spy;
4605 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004606};
4607
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608// Send a tap and respond, which should not cause an ANR.
4609TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4610 tapOnWindow();
4611 mWindow->consumeMotionDown();
4612 mWindow->consumeMotionUp();
4613 ASSERT_TRUE(mDispatcher->waitForIdle());
4614 mFakePolicy->assertNotifyAnrWasNotCalled();
4615}
4616
4617// Send a regular key and respond, which should not cause an ANR.
4618TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4621 ASSERT_TRUE(mDispatcher->waitForIdle());
4622 mFakePolicy->assertNotifyAnrWasNotCalled();
4623}
4624
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004625TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4626 mWindow->setFocusable(false);
4627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4628 mWindow->consumeFocusEvent(false);
4629
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004630 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004631 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004632 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4633 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004635 // Key will not go to window because we have no focused window.
4636 // The 'no focused window' ANR timer should start instead.
4637
4638 // Now, the focused application goes away.
4639 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4640 // The key should get dropped and there should be no ANR.
4641
4642 ASSERT_TRUE(mDispatcher->waitForIdle());
4643 mFakePolicy->assertNotifyAnrWasNotCalled();
4644}
4645
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004646// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004647// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4648// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004649TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4652 WINDOW_LOCATION));
4653
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004654 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4655 ASSERT_TRUE(sequenceNum);
4656 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004657 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004658
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004659 mWindow->finishEvent(*sequenceNum);
4660 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4661 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004662 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004663 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004664}
4665
4666// Send a key to the app and have the app not respond right away.
4667TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4668 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004670 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4671 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004672 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004673 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004674 ASSERT_TRUE(mDispatcher->waitForIdle());
4675}
4676
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677// We have a focused application, but no focused window
4678TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004679 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4681 mWindow->consumeFocusEvent(false);
4682
4683 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004685 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4686 WINDOW_LOCATION));
4687 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4688 mDispatcher->waitForIdle();
4689 mFakePolicy->assertNotifyAnrWasNotCalled();
4690
4691 // Once a focused event arrives, we get an ANR for this application
4692 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4693 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004696 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004697 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004699 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 ASSERT_TRUE(mDispatcher->waitForIdle());
4701}
4702
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004703/**
4704 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4705 * there will not be an ANR.
4706 */
4707TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4708 mWindow->setFocusable(false);
4709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4710 mWindow->consumeFocusEvent(false);
4711
4712 KeyEvent event;
4713 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4714 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4715
4716 // Define a valid key down event that is stale (too old).
4717 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4718 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4719 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4720
4721 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4722
4723 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004724 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004725 InputEventInjectionSync::WAIT_FOR_RESULT,
4726 INJECT_EVENT_TIMEOUT, policyFlags);
4727 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4728 << "Injection should fail because the event is stale";
4729
4730 ASSERT_TRUE(mDispatcher->waitForIdle());
4731 mFakePolicy->assertNotifyAnrWasNotCalled();
4732 mWindow->assertNoEvents();
4733}
4734
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004735// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004736// Make sure that we don't notify policy twice about the same ANR.
4737TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004738 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4740 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741
4742 // Once a focused event arrives, we get an ANR for this application
4743 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4744 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004745 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004747 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004748 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 const std::chrono::duration appTimeout =
4750 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004751 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004753 std::this_thread::sleep_for(appTimeout);
4754 // ANR should not be raised again. It is up to policy to do that if it desires.
4755 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004756
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004757 // If we now get a focused window, the ANR should stop, but the policy handles that via
4758 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759 ASSERT_TRUE(mDispatcher->waitForIdle());
4760}
4761
4762// We have a focused application, but no focused window
4763TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004764 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4766 mWindow->consumeFocusEvent(false);
4767
4768 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004771 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4772 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773
4774 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004775 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776
4777 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004778 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004779 ASSERT_TRUE(mDispatcher->waitForIdle());
4780 mWindow->assertNoEvents();
4781}
4782
4783/**
4784 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4785 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4786 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4787 * the ANR mechanism should still work.
4788 *
4789 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4790 * DOWN event, while not responding on the second one.
4791 */
4792TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4793 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4794 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4795 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4796 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4797 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799
4800 // Now send ACTION_UP, with identical timestamp
4801 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4802 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4803 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4804 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806
4807 // We have now sent down and up. Let's consume first event and then ANR on the second.
4808 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4809 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004810 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811}
4812
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004813// A spy window can receive an ANR
4814TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4815 sp<FakeWindowHandle> spy = addSpyWindow();
4816
4817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4818 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4819 WINDOW_LOCATION));
4820 mWindow->consumeMotionDown();
4821
4822 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4823 ASSERT_TRUE(sequenceNum);
4824 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004825 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004826
4827 spy->finishEvent(*sequenceNum);
4828 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4829 0 /*flags*/);
4830 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004831 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004832}
4833
4834// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004836TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4837 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4840 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843
4844 // Stuck on the ACTION_UP
4845 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004846 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004848 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004850 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4851 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852
4853 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4854 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004855 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004857 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858}
4859
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004860// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004862TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4863 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864
4865 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004866 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4867 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868
4869 mWindow->consumeMotionDown();
4870 // Stuck on the ACTION_UP
4871 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004872 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004874 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004876 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4877 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878
4879 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4880 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004881 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004883 spy->assertNoEvents();
4884}
4885
4886TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4887 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4888
4889 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4890
4891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4892 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4893 WINDOW_LOCATION));
4894
4895 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4896 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4897 ASSERT_TRUE(consumeSeq);
4898
Prabir Pradhanedd96402022-02-15 01:46:16 -08004899 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004900
4901 monitor.finishEvent(*consumeSeq);
4902 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4903
4904 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004905 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906}
4907
4908// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4909// process events, you don't get an anr. When the window later becomes unresponsive again, you
4910// get an ANR again.
4911// 1. tap -> block on ACTION_UP -> receive ANR
4912// 2. consume all pending events (= queue becomes healthy again)
4913// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4914TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4915 tapOnWindow();
4916
4917 mWindow->consumeMotionDown();
4918 // Block on ACTION_UP
4919 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004920 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004921 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4922 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004923 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mWindow->assertNoEvents();
4925
4926 tapOnWindow();
4927 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004928 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929 mWindow->consumeMotionUp();
4930
4931 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004932 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004933 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 mWindow->assertNoEvents();
4935}
4936
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004937// If a connection remains unresponsive for a while, make sure policy is only notified once about
4938// it.
4939TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4942 WINDOW_LOCATION));
4943
4944 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004945 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004947 // 'notifyConnectionUnresponsive' should only be called once per connection
4948 mFakePolicy->assertNotifyAnrWasNotCalled();
4949 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004950 mWindow->consumeMotionDown();
4951 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4952 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4953 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004954 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004955 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004956 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004957}
4958
4959/**
4960 * If a window is processing a motion event, and then a key event comes in, the key event should
4961 * not to to the focused window until the motion is processed.
4962 *
4963 * Warning!!!
4964 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4965 * and the injection timeout that we specify when injecting the key.
4966 * We must have the injection timeout (10ms) be smaller than
4967 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4968 *
4969 * If that value changes, this test should also change.
4970 */
4971TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4972 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4974
4975 tapOnWindow();
4976 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4977 ASSERT_TRUE(downSequenceNum);
4978 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4979 ASSERT_TRUE(upSequenceNum);
4980 // Don't finish the events yet, and send a key
4981 // Injection will "succeed" because we will eventually give up and send the key to the focused
4982 // window even if motions are still being processed. But because the injection timeout is short,
4983 // we will receive INJECTION_TIMED_OUT as the result.
4984
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004985 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004987 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4988 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004989 // Key will not be sent to the window, yet, because the window is still processing events
4990 // and the key remains pending, waiting for the touch events to be processed
4991 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4992 ASSERT_FALSE(keySequenceNum);
4993
4994 std::this_thread::sleep_for(500ms);
4995 // if we wait long enough though, dispatcher will give up, and still send the key
4996 // to the focused window, even though we have not yet finished the motion event
4997 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4998 mWindow->finishEvent(*downSequenceNum);
4999 mWindow->finishEvent(*upSequenceNum);
5000}
5001
5002/**
5003 * If a window is processing a motion event, and then a key event comes in, the key event should
5004 * not go to the focused window until the motion is processed.
5005 * If then a new motion comes in, then the pending key event should be going to the currently
5006 * focused window right away.
5007 */
5008TEST_F(InputDispatcherSingleWindowAnr,
5009 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5010 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5012
5013 tapOnWindow();
5014 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5015 ASSERT_TRUE(downSequenceNum);
5016 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5017 ASSERT_TRUE(upSequenceNum);
5018 // Don't finish the events yet, and send a key
5019 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005021 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005022 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005023 // At this point, key is still pending, and should not be sent to the application yet.
5024 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5025 ASSERT_FALSE(keySequenceNum);
5026
5027 // Now tap down again. It should cause the pending key to go to the focused window right away.
5028 tapOnWindow();
5029 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5030 // the other events yet. We can finish events in any order.
5031 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5032 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5033 mWindow->consumeMotionDown();
5034 mWindow->consumeMotionUp();
5035 mWindow->assertNoEvents();
5036}
5037
5038class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5039 virtual void SetUp() override {
5040 InputDispatcherTest::SetUp();
5041
Chris Yea209fde2020-07-22 13:54:51 -07005042 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005043 mApplication->setDispatchingTimeout(10ms);
5044 mUnfocusedWindow =
5045 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
5046 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005048 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005049
5050 mFocusedWindow =
5051 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005052 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005053 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054
5055 // Set focused application.
5056 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005057 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005058
5059 // Expect one focus window exist in display.
5060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005061 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005062 mFocusedWindow->consumeFocusEvent(true);
5063 }
5064
5065 virtual void TearDown() override {
5066 InputDispatcherTest::TearDown();
5067
5068 mUnfocusedWindow.clear();
5069 mFocusedWindow.clear();
5070 }
5071
5072protected:
Chris Yea209fde2020-07-22 13:54:51 -07005073 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005074 sp<FakeWindowHandle> mUnfocusedWindow;
5075 sp<FakeWindowHandle> mFocusedWindow;
5076 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5077 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5078 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5079
5080 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5081
5082 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5083
5084private:
5085 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005087 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5088 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5091 location));
5092 }
5093};
5094
5095// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5096// should be ANR'd first.
5097TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5100 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005101 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102 mFocusedWindow->consumeMotionDown();
5103 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5104 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5105 // We consumed all events, so no ANR
5106 ASSERT_TRUE(mDispatcher->waitForIdle());
5107 mFakePolicy->assertNotifyAnrWasNotCalled();
5108
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5111 FOCUSED_WINDOW_LOCATION));
5112 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5113 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005114
5115 const std::chrono::duration timeout =
5116 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005117 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005118 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5119 // sequence to make it consistent
5120 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005122 mFocusedWindow->consumeMotionDown();
5123 // This cancel is generated because the connection was unresponsive
5124 mFocusedWindow->consumeMotionCancel();
5125 mFocusedWindow->assertNoEvents();
5126 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005127 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005128 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5129 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005130 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131}
5132
5133// If we have 2 windows with identical timeouts that are both unresponsive,
5134// it doesn't matter which order they should have ANR.
5135// But we should receive ANR for both.
5136TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5137 // Set the timeout for unfocused window to match the focused window
5138 mUnfocusedWindow->setDispatchingTimeout(10ms);
5139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5140
5141 tapOnFocusedWindow();
5142 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005143 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5144 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5145 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005146
5147 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005148 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5149 mFocusedWindow->getToken() == anrConnectionToken2);
5150 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5151 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152
5153 ASSERT_TRUE(mDispatcher->waitForIdle());
5154 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005155
5156 mFocusedWindow->consumeMotionDown();
5157 mFocusedWindow->consumeMotionUp();
5158 mUnfocusedWindow->consumeMotionOutside();
5159
Prabir Pradhanedd96402022-02-15 01:46:16 -08005160 sp<IBinder> responsiveToken1, responsiveToken2;
5161 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5162 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005163
5164 // Both applications should be marked as responsive, in any order
5165 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5166 mFocusedWindow->getToken() == responsiveToken2);
5167 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5168 mUnfocusedWindow->getToken() == responsiveToken2);
5169 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005170}
5171
5172// If a window is already not responding, the second tap on the same window should be ignored.
5173// We should also log an error to account for the dropped event (not tested here).
5174// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5175TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5176 tapOnFocusedWindow();
5177 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5178 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5179 // Receive the events, but don't respond
5180 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5181 ASSERT_TRUE(downEventSequenceNum);
5182 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5183 ASSERT_TRUE(upEventSequenceNum);
5184 const std::chrono::duration timeout =
5185 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005186 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005187
5188 // Tap once again
5189 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005190 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005191 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5192 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005193 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005194 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5195 FOCUSED_WINDOW_LOCATION));
5196 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5197 // valid touch target
5198 mUnfocusedWindow->assertNoEvents();
5199
5200 // Consume the first tap
5201 mFocusedWindow->finishEvent(*downEventSequenceNum);
5202 mFocusedWindow->finishEvent(*upEventSequenceNum);
5203 ASSERT_TRUE(mDispatcher->waitForIdle());
5204 // The second tap did not go to the focused window
5205 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005206 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005207 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5208 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005209 mFakePolicy->assertNotifyAnrWasNotCalled();
5210}
5211
5212// If you tap outside of all windows, there will not be ANR
5213TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005214 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5216 LOCATION_OUTSIDE_ALL_WINDOWS));
5217 ASSERT_TRUE(mDispatcher->waitForIdle());
5218 mFakePolicy->assertNotifyAnrWasNotCalled();
5219}
5220
5221// Since the focused window is paused, tapping on it should not produce any events
5222TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5223 mFocusedWindow->setPaused(true);
5224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5225
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005226 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5228 FOCUSED_WINDOW_LOCATION));
5229
5230 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5231 ASSERT_TRUE(mDispatcher->waitForIdle());
5232 // Should not ANR because the window is paused, and touches shouldn't go to it
5233 mFakePolicy->assertNotifyAnrWasNotCalled();
5234
5235 mFocusedWindow->assertNoEvents();
5236 mUnfocusedWindow->assertNoEvents();
5237}
5238
5239/**
5240 * If a window is processing a motion event, and then a key event comes in, the key event should
5241 * not to to the focused window until the motion is processed.
5242 * If a different window becomes focused at this time, the key should go to that window instead.
5243 *
5244 * Warning!!!
5245 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5246 * and the injection timeout that we specify when injecting the key.
5247 * We must have the injection timeout (10ms) be smaller than
5248 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5249 *
5250 * If that value changes, this test should also change.
5251 */
5252TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5253 // Set a long ANR timeout to prevent it from triggering
5254 mFocusedWindow->setDispatchingTimeout(2s);
5255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5256
5257 tapOnUnfocusedWindow();
5258 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5259 ASSERT_TRUE(downSequenceNum);
5260 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5261 ASSERT_TRUE(upSequenceNum);
5262 // Don't finish the events yet, and send a key
5263 // Injection will succeed because we will eventually give up and send the key to the focused
5264 // window even if motions are still being processed.
5265
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005266 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005267 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005268 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005270 // Key will not be sent to the window, yet, because the window is still processing events
5271 // and the key remains pending, waiting for the touch events to be processed
5272 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5273 ASSERT_FALSE(keySequenceNum);
5274
5275 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005276 mFocusedWindow->setFocusable(false);
5277 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005279 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005280
5281 // Focus events should precede the key events
5282 mUnfocusedWindow->consumeFocusEvent(true);
5283 mFocusedWindow->consumeFocusEvent(false);
5284
5285 // Finish the tap events, which should unblock dispatcher
5286 mUnfocusedWindow->finishEvent(*downSequenceNum);
5287 mUnfocusedWindow->finishEvent(*upSequenceNum);
5288
5289 // Now that all queues are cleared and no backlog in the connections, the key event
5290 // can finally go to the newly focused "mUnfocusedWindow".
5291 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5292 mFocusedWindow->assertNoEvents();
5293 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005294 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005295}
5296
5297// When the touch stream is split across 2 windows, and one of them does not respond,
5298// then ANR should be raised and the touch should be canceled for the unresponsive window.
5299// The other window should not be affected by that.
5300TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5301 // Touch Window 1
5302 NotifyMotionArgs motionArgs =
5303 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5304 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5305 mDispatcher->notifyMotion(&motionArgs);
5306 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5307 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5308
5309 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005310 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5311 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005312 mDispatcher->notifyMotion(&motionArgs);
5313
5314 const std::chrono::duration timeout =
5315 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005316 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317
5318 mUnfocusedWindow->consumeMotionDown();
5319 mFocusedWindow->consumeMotionDown();
5320 // Focused window may or may not receive ACTION_MOVE
5321 // But it should definitely receive ACTION_CANCEL due to the ANR
5322 InputEvent* event;
5323 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5324 ASSERT_TRUE(moveOrCancelSequenceNum);
5325 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5326 ASSERT_NE(nullptr, event);
5327 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5328 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5329 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5330 mFocusedWindow->consumeMotionCancel();
5331 } else {
5332 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5333 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005334 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005335 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5336 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005337
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005338 mUnfocusedWindow->assertNoEvents();
5339 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005340 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341}
5342
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005343/**
5344 * If we have no focused window, and a key comes in, we start the ANR timer.
5345 * The focused application should add a focused window before the timer runs out to prevent ANR.
5346 *
5347 * If the user touches another application during this time, the key should be dropped.
5348 * Next, if a new focused window comes in, without toggling the focused application,
5349 * then no ANR should occur.
5350 *
5351 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5352 * but in some cases the policy may not update the focused application.
5353 */
5354TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5355 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5356 std::make_shared<FakeApplicationHandle>();
5357 focusedApplication->setDispatchingTimeout(60ms);
5358 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5359 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5360 mFocusedWindow->setFocusable(false);
5361
5362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5363 mFocusedWindow->consumeFocusEvent(false);
5364
5365 // Send a key. The ANR timer should start because there is no focused window.
5366 // 'focusedApplication' will get blamed if this timer completes.
5367 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005368 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005369 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005370 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5371 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005373
5374 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5375 // then the injected touches won't cause the focused event to get dropped.
5376 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5377 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5378 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5379 // For this test, it means that the key would get delivered to the window once it becomes
5380 // focused.
5381 std::this_thread::sleep_for(10ms);
5382
5383 // Touch unfocused window. This should force the pending key to get dropped.
5384 NotifyMotionArgs motionArgs =
5385 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5386 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5387 mDispatcher->notifyMotion(&motionArgs);
5388
5389 // We do not consume the motion right away, because that would require dispatcher to first
5390 // process (== drop) the key event, and by that time, ANR will be raised.
5391 // Set the focused window first.
5392 mFocusedWindow->setFocusable(true);
5393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5394 setFocusedWindow(mFocusedWindow);
5395 mFocusedWindow->consumeFocusEvent(true);
5396 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5397 // to another application. This could be a bug / behaviour in the policy.
5398
5399 mUnfocusedWindow->consumeMotionDown();
5400
5401 ASSERT_TRUE(mDispatcher->waitForIdle());
5402 // Should not ANR because we actually have a focused window. It was just added too slowly.
5403 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5404}
5405
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005406// These tests ensure we cannot send touch events to a window that's positioned behind a window
5407// that has feature NO_INPUT_CHANNEL.
5408// Layout:
5409// Top (closest to user)
5410// mNoInputWindow (above all windows)
5411// mBottomWindow
5412// Bottom (furthest from user)
5413class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5414 virtual void SetUp() override {
5415 InputDispatcherTest::SetUp();
5416
5417 mApplication = std::make_shared<FakeApplicationHandle>();
5418 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5419 "Window without input channel", ADISPLAY_ID_DEFAULT,
5420 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5421
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005422 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005423 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5424 // It's perfectly valid for this window to not have an associated input channel
5425
5426 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5427 ADISPLAY_ID_DEFAULT);
5428 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5429
5430 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5431 }
5432
5433protected:
5434 std::shared_ptr<FakeApplicationHandle> mApplication;
5435 sp<FakeWindowHandle> mNoInputWindow;
5436 sp<FakeWindowHandle> mBottomWindow;
5437};
5438
5439TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5440 PointF touchedPoint = {10, 10};
5441
5442 NotifyMotionArgs motionArgs =
5443 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5444 ADISPLAY_ID_DEFAULT, {touchedPoint});
5445 mDispatcher->notifyMotion(&motionArgs);
5446
5447 mNoInputWindow->assertNoEvents();
5448 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5449 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5450 // and therefore should prevent mBottomWindow from receiving touches
5451 mBottomWindow->assertNoEvents();
5452}
5453
5454/**
5455 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5456 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5457 */
5458TEST_F(InputDispatcherMultiWindowOcclusionTests,
5459 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5460 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5461 "Window with input channel and NO_INPUT_CHANNEL",
5462 ADISPLAY_ID_DEFAULT);
5463
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005464 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005465 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5467
5468 PointF touchedPoint = {10, 10};
5469
5470 NotifyMotionArgs motionArgs =
5471 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5472 ADISPLAY_ID_DEFAULT, {touchedPoint});
5473 mDispatcher->notifyMotion(&motionArgs);
5474
5475 mNoInputWindow->assertNoEvents();
5476 mBottomWindow->assertNoEvents();
5477}
5478
Vishnu Nair958da932020-08-21 17:12:37 -07005479class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5480protected:
5481 std::shared_ptr<FakeApplicationHandle> mApp;
5482 sp<FakeWindowHandle> mWindow;
5483 sp<FakeWindowHandle> mMirror;
5484
5485 virtual void SetUp() override {
5486 InputDispatcherTest::SetUp();
5487 mApp = std::make_shared<FakeApplicationHandle>();
5488 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5489 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5490 mWindow->getToken());
5491 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5492 mWindow->setFocusable(true);
5493 mMirror->setFocusable(true);
5494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5495 }
5496};
5497
5498TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5499 // Request focus on a mirrored window
5500 setFocusedWindow(mMirror);
5501
5502 // window gets focused
5503 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5505 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005506 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5507}
5508
5509// A focused & mirrored window remains focused only if the window and its mirror are both
5510// focusable.
5511TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5512 setFocusedWindow(mMirror);
5513
5514 // window gets focused
5515 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5517 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005518 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5520 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005521 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5522
5523 mMirror->setFocusable(false);
5524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5525
5526 // window loses focus since one of the windows associated with the token in not focusable
5527 mWindow->consumeFocusEvent(false);
5528
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005529 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5530 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005531 mWindow->assertNoEvents();
5532}
5533
5534// A focused & mirrored window remains focused until the window and its mirror both become
5535// invisible.
5536TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5537 setFocusedWindow(mMirror);
5538
5539 // window gets focused
5540 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5542 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005543 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5545 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005546 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5547
5548 mMirror->setVisible(false);
5549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5550
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5552 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005553 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5555 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005556 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5557
5558 mWindow->setVisible(false);
5559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5560
5561 // window loses focus only after all windows associated with the token become invisible.
5562 mWindow->consumeFocusEvent(false);
5563
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005564 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5565 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005566 mWindow->assertNoEvents();
5567}
5568
5569// A focused & mirrored window remains focused until both windows are removed.
5570TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5571 setFocusedWindow(mMirror);
5572
5573 // window gets focused
5574 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5576 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005577 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5579 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005580 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5581
5582 // single window is removed but the window token remains focused
5583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5584
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5586 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005587 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5589 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005590 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5591
5592 // Both windows are removed
5593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5594 mWindow->consumeFocusEvent(false);
5595
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005596 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5597 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005598 mWindow->assertNoEvents();
5599}
5600
5601// Focus request can be pending until one window becomes visible.
5602TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5603 // Request focus on an invisible mirror.
5604 mWindow->setVisible(false);
5605 mMirror->setVisible(false);
5606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5607 setFocusedWindow(mMirror);
5608
5609 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005611 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005612 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005613
5614 mMirror->setVisible(true);
5615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5616
5617 // window gets focused
5618 mWindow->consumeFocusEvent(true);
5619 // window gets the pending key event
5620 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5621}
Prabir Pradhan99987712020-11-10 18:43:05 -08005622
5623class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5624protected:
5625 std::shared_ptr<FakeApplicationHandle> mApp;
5626 sp<FakeWindowHandle> mWindow;
5627 sp<FakeWindowHandle> mSecondWindow;
5628
5629 void SetUp() override {
5630 InputDispatcherTest::SetUp();
5631 mApp = std::make_shared<FakeApplicationHandle>();
5632 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5633 mWindow->setFocusable(true);
5634 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5635 mSecondWindow->setFocusable(true);
5636
5637 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5639
5640 setFocusedWindow(mWindow);
5641 mWindow->consumeFocusEvent(true);
5642 }
5643
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005644 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5645 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005646 mDispatcher->notifyPointerCaptureChanged(&args);
5647 }
5648
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005649 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5650 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005651 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005652 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5653 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005654 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005655 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005656 }
5657};
5658
5659TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5660 // Ensure that capture cannot be obtained for unfocused windows.
5661 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5662 mFakePolicy->assertSetPointerCaptureNotCalled();
5663 mSecondWindow->assertNoEvents();
5664
5665 // Ensure that capture can be enabled from the focus window.
5666 requestAndVerifyPointerCapture(mWindow, true);
5667
5668 // Ensure that capture cannot be disabled from a window that does not have capture.
5669 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5670 mFakePolicy->assertSetPointerCaptureNotCalled();
5671
5672 // Ensure that capture can be disabled from the window with capture.
5673 requestAndVerifyPointerCapture(mWindow, false);
5674}
5675
5676TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005677 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005678
5679 setFocusedWindow(mSecondWindow);
5680
5681 // Ensure that the capture disabled event was sent first.
5682 mWindow->consumeCaptureEvent(false);
5683 mWindow->consumeFocusEvent(false);
5684 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005685 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005686
5687 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005688 notifyPointerCaptureChanged({});
5689 notifyPointerCaptureChanged(request);
5690 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005691 mWindow->assertNoEvents();
5692 mSecondWindow->assertNoEvents();
5693 mFakePolicy->assertSetPointerCaptureNotCalled();
5694}
5695
5696TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005697 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005698
5699 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005700 notifyPointerCaptureChanged({});
5701 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005702
5703 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005704 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005705 mWindow->consumeCaptureEvent(false);
5706 mWindow->assertNoEvents();
5707}
5708
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005709TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5710 requestAndVerifyPointerCapture(mWindow, true);
5711
5712 // The first window loses focus.
5713 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005714 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005715 mWindow->consumeCaptureEvent(false);
5716
5717 // Request Pointer Capture from the second window before the notification from InputReader
5718 // arrives.
5719 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005720 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005721
5722 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005723 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005724
5725 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005726 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005727
5728 mSecondWindow->consumeFocusEvent(true);
5729 mSecondWindow->consumeCaptureEvent(true);
5730}
5731
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005732TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5733 // App repeatedly enables and disables capture.
5734 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5735 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5736 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5737 mFakePolicy->assertSetPointerCaptureCalled(false);
5738 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5739 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5740
5741 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5742 // first request is now stale, this should do nothing.
5743 notifyPointerCaptureChanged(firstRequest);
5744 mWindow->assertNoEvents();
5745
5746 // InputReader notifies that the second request was enabled.
5747 notifyPointerCaptureChanged(secondRequest);
5748 mWindow->consumeCaptureEvent(true);
5749}
5750
Prabir Pradhan7092e262022-05-03 16:51:09 +00005751TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5752 requestAndVerifyPointerCapture(mWindow, true);
5753
5754 // App toggles pointer capture off and on.
5755 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5756 mFakePolicy->assertSetPointerCaptureCalled(false);
5757
5758 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5759 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5760
5761 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5762 // preceding "disable" request.
5763 notifyPointerCaptureChanged(enableRequest);
5764
5765 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5766 // any notifications.
5767 mWindow->assertNoEvents();
5768}
5769
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005770class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5771protected:
5772 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005773
5774 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5775 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5776
5777 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5778 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5779
5780 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5781 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5782 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5783 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5784 MAXIMUM_OBSCURING_OPACITY);
5785
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005786 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005787 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005788 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005789
5790 sp<FakeWindowHandle> mTouchWindow;
5791
5792 virtual void SetUp() override {
5793 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005794 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005795 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5796 }
5797
5798 virtual void TearDown() override {
5799 InputDispatcherTest::TearDown();
5800 mTouchWindow.clear();
5801 }
5802
chaviw3277faf2021-05-19 16:45:23 -05005803 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5804 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005805 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005806 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005807 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005808 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005809 return window;
5810 }
5811
5812 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5813 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5814 sp<FakeWindowHandle> window =
5815 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5816 // Generate an arbitrary PID based on the UID
5817 window->setOwnerInfo(1777 + (uid % 10000), uid);
5818 return window;
5819 }
5820
5821 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5822 NotifyMotionArgs args =
5823 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5824 ADISPLAY_ID_DEFAULT, points);
5825 mDispatcher->notifyMotion(&args);
5826 }
5827};
5828
5829TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005830 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005831 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005833
5834 touch();
5835
5836 mTouchWindow->assertNoEvents();
5837}
5838
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005839TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005840 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5841 const sp<FakeWindowHandle>& w =
5842 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5844
5845 touch();
5846
5847 mTouchWindow->assertNoEvents();
5848}
5849
5850TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005851 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5852 const sp<FakeWindowHandle>& w =
5853 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5855
5856 touch();
5857
5858 w->assertNoEvents();
5859}
5860
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005861TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005862 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005864
5865 touch();
5866
5867 mTouchWindow->consumeAnyMotionDown();
5868}
5869
5870TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005871 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005872 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005873 w->setFrame(Rect(0, 0, 50, 50));
5874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005875
5876 touch({PointF{100, 100}});
5877
5878 mTouchWindow->consumeAnyMotionDown();
5879}
5880
5881TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005882 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005883 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5885
5886 touch();
5887
5888 mTouchWindow->consumeAnyMotionDown();
5889}
5890
5891TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5892 const sp<FakeWindowHandle>& w =
5893 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005895
5896 touch();
5897
5898 mTouchWindow->consumeAnyMotionDown();
5899}
5900
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005901TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5902 const sp<FakeWindowHandle>& w =
5903 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5905
5906 touch();
5907
5908 w->assertNoEvents();
5909}
5910
5911/**
5912 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5913 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5914 * window, the occluding window will still receive ACTION_OUTSIDE event.
5915 */
5916TEST_F(InputDispatcherUntrustedTouchesTest,
5917 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5918 const sp<FakeWindowHandle>& w =
5919 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005920 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5922
5923 touch();
5924
5925 w->consumeMotionOutside();
5926}
5927
5928TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5929 const sp<FakeWindowHandle>& w =
5930 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005931 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5933
5934 touch();
5935
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005936 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005937}
5938
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005939TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005940 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005941 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5942 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5944
5945 touch();
5946
5947 mTouchWindow->consumeAnyMotionDown();
5948}
5949
5950TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5951 const sp<FakeWindowHandle>& w =
5952 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5953 MAXIMUM_OBSCURING_OPACITY);
5954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005955
5956 touch();
5957
5958 mTouchWindow->consumeAnyMotionDown();
5959}
5960
5961TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005962 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005963 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5964 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5966
5967 touch();
5968
5969 mTouchWindow->assertNoEvents();
5970}
5971
5972TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5973 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5974 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005975 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5976 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005977 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005978 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5979 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5981
5982 touch();
5983
5984 mTouchWindow->assertNoEvents();
5985}
5986
5987TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5988 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5989 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005990 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5991 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005992 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005993 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5994 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5996
5997 touch();
5998
5999 mTouchWindow->consumeAnyMotionDown();
6000}
6001
6002TEST_F(InputDispatcherUntrustedTouchesTest,
6003 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6004 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006005 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6006 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006007 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006008 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6009 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6011
6012 touch();
6013
6014 mTouchWindow->consumeAnyMotionDown();
6015}
6016
6017TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6018 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006019 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6020 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006021 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006022 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6023 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006025
6026 touch();
6027
6028 mTouchWindow->assertNoEvents();
6029}
6030
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006031TEST_F(InputDispatcherUntrustedTouchesTest,
6032 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6033 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006034 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6035 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006036 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006037 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6038 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6040
6041 touch();
6042
6043 mTouchWindow->assertNoEvents();
6044}
6045
6046TEST_F(InputDispatcherUntrustedTouchesTest,
6047 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6048 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006049 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6050 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006051 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006052 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6053 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6055
6056 touch();
6057
6058 mTouchWindow->consumeAnyMotionDown();
6059}
6060
6061TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6062 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006063 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6064 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6066
6067 touch();
6068
6069 mTouchWindow->consumeAnyMotionDown();
6070}
6071
6072TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6073 const sp<FakeWindowHandle>& w =
6074 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6075 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6076
6077 touch();
6078
6079 mTouchWindow->consumeAnyMotionDown();
6080}
6081
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006082TEST_F(InputDispatcherUntrustedTouchesTest,
6083 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6084 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6085 const sp<FakeWindowHandle>& w =
6086 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6088
6089 touch();
6090
6091 mTouchWindow->assertNoEvents();
6092}
6093
6094TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6095 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6096 const sp<FakeWindowHandle>& w =
6097 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6099
6100 touch();
6101
6102 mTouchWindow->consumeAnyMotionDown();
6103}
6104
6105TEST_F(InputDispatcherUntrustedTouchesTest,
6106 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6107 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6108 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006109 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6110 OPACITY_ABOVE_THRESHOLD);
6111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6112
6113 touch();
6114
6115 mTouchWindow->consumeAnyMotionDown();
6116}
6117
6118TEST_F(InputDispatcherUntrustedTouchesTest,
6119 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6120 const sp<FakeWindowHandle>& w1 =
6121 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6122 OPACITY_BELOW_THRESHOLD);
6123 const sp<FakeWindowHandle>& w2 =
6124 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6125 OPACITY_BELOW_THRESHOLD);
6126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6127
6128 touch();
6129
6130 mTouchWindow->assertNoEvents();
6131}
6132
6133/**
6134 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6135 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6136 * (which alone would result in allowing touches) does not affect the blocking behavior.
6137 */
6138TEST_F(InputDispatcherUntrustedTouchesTest,
6139 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6140 const sp<FakeWindowHandle>& wB =
6141 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6142 OPACITY_BELOW_THRESHOLD);
6143 const sp<FakeWindowHandle>& wC =
6144 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6145 OPACITY_BELOW_THRESHOLD);
6146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6147
6148 touch();
6149
6150 mTouchWindow->assertNoEvents();
6151}
6152
6153/**
6154 * This test is testing that a window from a different UID but with same application token doesn't
6155 * block the touch. Apps can share the application token for close UI collaboration for example.
6156 */
6157TEST_F(InputDispatcherUntrustedTouchesTest,
6158 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6159 const sp<FakeWindowHandle>& w =
6160 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6161 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6163
6164 touch();
6165
6166 mTouchWindow->consumeAnyMotionDown();
6167}
6168
arthurhungb89ccb02020-12-30 16:19:01 +08006169class InputDispatcherDragTests : public InputDispatcherTest {
6170protected:
6171 std::shared_ptr<FakeApplicationHandle> mApp;
6172 sp<FakeWindowHandle> mWindow;
6173 sp<FakeWindowHandle> mSecondWindow;
6174 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006175 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006176 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6177 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006178
6179 void SetUp() override {
6180 InputDispatcherTest::SetUp();
6181 mApp = std::make_shared<FakeApplicationHandle>();
6182 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6183 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006184
6185 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6186 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006187
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006188 mSpyWindow = new FakeWindowHandle(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
6189 mSpyWindow->setSpy(true);
6190 mSpyWindow->setTrustedOverlay(true);
6191 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6192
arthurhungb89ccb02020-12-30 16:19:01 +08006193 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006195 }
6196
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006197 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6198 switch (fromSource) {
6199 case AINPUT_SOURCE_TOUCHSCREEN:
6200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6201 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6202 ADISPLAY_ID_DEFAULT, {50, 50}))
6203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6204 break;
6205 case AINPUT_SOURCE_STYLUS:
6206 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6207 injectMotionEvent(
6208 mDispatcher,
6209 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6210 AINPUT_SOURCE_STYLUS)
6211 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6212 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6213 .x(50)
6214 .y(50))
6215 .build()));
6216 break;
6217 case AINPUT_SOURCE_MOUSE:
6218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6219 injectMotionEvent(
6220 mDispatcher,
6221 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6222 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6223 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6224 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6225 .x(50)
6226 .y(50))
6227 .build()));
6228 break;
6229 default:
6230 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6231 }
arthurhungb89ccb02020-12-30 16:19:01 +08006232
6233 // Window should receive motion event.
6234 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006235 // Spy window should also receive motion event
6236 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006237 }
6238
6239 // Start performing drag, we will create a drag window and transfer touch to it.
6240 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6241 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006242 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006243 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006244 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006245 }
arthurhungb89ccb02020-12-30 16:19:01 +08006246
6247 // The drag window covers the entire display
6248 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006249 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006250 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006251 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006252
6253 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006254 bool transferred =
6255 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6256 true /* isDragDrop */);
6257 if (transferred) {
6258 mWindow->consumeMotionCancel();
6259 mDragWindow->consumeMotionDown();
6260 }
6261 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006262 }
6263};
6264
6265TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006266 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006267
6268 // Move on window.
6269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6270 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6271 ADISPLAY_ID_DEFAULT, {50, 50}))
6272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6273 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6274 mWindow->consumeDragEvent(false, 50, 50);
6275 mSecondWindow->assertNoEvents();
6276
6277 // Move to another window.
6278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6279 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6280 ADISPLAY_ID_DEFAULT, {150, 50}))
6281 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6282 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6283 mWindow->consumeDragEvent(true, 150, 50);
6284 mSecondWindow->consumeDragEvent(false, 50, 50);
6285
6286 // Move back to original window.
6287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6288 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6289 ADISPLAY_ID_DEFAULT, {50, 50}))
6290 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6291 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6292 mWindow->consumeDragEvent(false, 50, 50);
6293 mSecondWindow->consumeDragEvent(true, -50, 50);
6294
6295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6296 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6297 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6298 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6299 mWindow->assertNoEvents();
6300 mSecondWindow->assertNoEvents();
6301}
6302
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006303TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006304 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006305
6306 // No cancel event after drag start
6307 mSpyWindow->assertNoEvents();
6308
6309 const MotionEvent secondFingerDownEvent =
6310 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6311 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6312 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6313 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6314 .build();
6315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6316 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6317 InputEventInjectionSync::WAIT_FOR_RESULT))
6318 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6319
6320 // Receives cancel for first pointer after next pointer down
6321 mSpyWindow->consumeMotionCancel();
6322 mSpyWindow->consumeMotionDown();
6323
6324 mSpyWindow->assertNoEvents();
6325}
6326
arthurhungf452d0b2021-01-06 00:19:52 +08006327TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006328 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006329
6330 // Move on window.
6331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6332 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6333 ADISPLAY_ID_DEFAULT, {50, 50}))
6334 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6335 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6336 mWindow->consumeDragEvent(false, 50, 50);
6337 mSecondWindow->assertNoEvents();
6338
6339 // Move to another window.
6340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6341 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6342 ADISPLAY_ID_DEFAULT, {150, 50}))
6343 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6344 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6345 mWindow->consumeDragEvent(true, 150, 50);
6346 mSecondWindow->consumeDragEvent(false, 50, 50);
6347
6348 // drop to another window.
6349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6350 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6351 {150, 50}))
6352 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6353 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6354 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6355 mWindow->assertNoEvents();
6356 mSecondWindow->assertNoEvents();
6357}
6358
arthurhung6d4bed92021-03-17 11:59:33 +08006359TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006360 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006361
6362 // Move on window and keep button pressed.
6363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6364 injectMotionEvent(mDispatcher,
6365 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6366 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6367 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6368 .x(50)
6369 .y(50))
6370 .build()))
6371 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6372 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6373 mWindow->consumeDragEvent(false, 50, 50);
6374 mSecondWindow->assertNoEvents();
6375
6376 // Move to another window and release button, expect to drop item.
6377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6378 injectMotionEvent(mDispatcher,
6379 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6380 .buttonState(0)
6381 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6382 .x(150)
6383 .y(50))
6384 .build()))
6385 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6386 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6387 mWindow->assertNoEvents();
6388 mSecondWindow->assertNoEvents();
6389 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6390
6391 // nothing to the window.
6392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6393 injectMotionEvent(mDispatcher,
6394 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6395 .buttonState(0)
6396 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6397 .x(150)
6398 .y(50))
6399 .build()))
6400 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6401 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6402 mWindow->assertNoEvents();
6403 mSecondWindow->assertNoEvents();
6404}
6405
Arthur Hung54745652022-04-20 07:17:41 +00006406TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006407 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006408
6409 // Set second window invisible.
6410 mSecondWindow->setVisible(false);
6411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6412
6413 // Move on window.
6414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6415 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6416 ADISPLAY_ID_DEFAULT, {50, 50}))
6417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6418 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6419 mWindow->consumeDragEvent(false, 50, 50);
6420 mSecondWindow->assertNoEvents();
6421
6422 // Move to another window.
6423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6424 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6425 ADISPLAY_ID_DEFAULT, {150, 50}))
6426 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6427 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6428 mWindow->consumeDragEvent(true, 150, 50);
6429 mSecondWindow->assertNoEvents();
6430
6431 // drop to another window.
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6434 {150, 50}))
6435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6436 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6437 mFakePolicy->assertDropTargetEquals(nullptr);
6438 mWindow->assertNoEvents();
6439 mSecondWindow->assertNoEvents();
6440}
6441
Arthur Hung54745652022-04-20 07:17:41 +00006442TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006443 // Ensure window could track pointerIds if it didn't support split touch.
6444 mWindow->setPreventSplitting(true);
6445
Arthur Hung54745652022-04-20 07:17:41 +00006446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6447 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6448 {50, 50}))
6449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6450 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6451
6452 const MotionEvent secondFingerDownEvent =
6453 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6454 .displayId(ADISPLAY_ID_DEFAULT)
6455 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6456 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6457 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6458 .build();
6459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6460 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6461 InputEventInjectionSync::WAIT_FOR_RESULT))
6462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6463 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6464
6465 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006466 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006467}
6468
6469TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6470 // First down on second window.
6471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6472 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6473 {150, 50}))
6474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6475
6476 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6477
6478 // Second down on first window.
6479 const MotionEvent secondFingerDownEvent =
6480 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6481 .displayId(ADISPLAY_ID_DEFAULT)
6482 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6483 .pointer(
6484 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6485 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6486 .build();
6487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6488 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6489 InputEventInjectionSync::WAIT_FOR_RESULT))
6490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6491 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6492
6493 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006494 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006495
6496 // Move on window.
6497 const MotionEvent secondFingerMoveEvent =
6498 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6499 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6500 .pointer(
6501 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6502 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6503 .build();
6504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6505 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6506 InputEventInjectionSync::WAIT_FOR_RESULT));
6507 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6508 mWindow->consumeDragEvent(false, 50, 50);
6509 mSecondWindow->consumeMotionMove();
6510
6511 // Release the drag pointer should perform drop.
6512 const MotionEvent secondFingerUpEvent =
6513 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6514 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6515 .pointer(
6516 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6517 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6518 .build();
6519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6520 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6521 InputEventInjectionSync::WAIT_FOR_RESULT));
6522 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6523 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6524 mWindow->assertNoEvents();
6525 mSecondWindow->consumeMotionMove();
6526}
6527
Arthur Hung3915c1f2022-05-31 07:17:17 +00006528TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006529 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006530
6531 // Update window of second display.
6532 sp<FakeWindowHandle> windowInSecondary =
6533 new FakeWindowHandle(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
6534 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6535
6536 // Let second display has a touch state.
6537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6538 injectMotionEvent(mDispatcher,
6539 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6540 AINPUT_SOURCE_TOUCHSCREEN)
6541 .displayId(SECOND_DISPLAY_ID)
6542 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6543 .x(100)
6544 .y(100))
6545 .build()));
6546 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6547 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6548 // Update window again.
6549 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6550
6551 // Move on window.
6552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6553 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6554 ADISPLAY_ID_DEFAULT, {50, 50}))
6555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6556 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6557 mWindow->consumeDragEvent(false, 50, 50);
6558 mSecondWindow->assertNoEvents();
6559
6560 // Move to another window.
6561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6562 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6563 ADISPLAY_ID_DEFAULT, {150, 50}))
6564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6565 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6566 mWindow->consumeDragEvent(true, 150, 50);
6567 mSecondWindow->consumeDragEvent(false, 50, 50);
6568
6569 // drop to another window.
6570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6571 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6572 {150, 50}))
6573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6574 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6575 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6576 mWindow->assertNoEvents();
6577 mSecondWindow->assertNoEvents();
6578}
6579
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006580TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6581 startDrag(true, AINPUT_SOURCE_MOUSE);
6582 // Move on window.
6583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6584 injectMotionEvent(mDispatcher,
6585 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6586 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6587 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6588 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6589 .x(50)
6590 .y(50))
6591 .build()))
6592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6593 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6594 mWindow->consumeDragEvent(false, 50, 50);
6595 mSecondWindow->assertNoEvents();
6596
6597 // Move to another window.
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionEvent(mDispatcher,
6600 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6601 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6602 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6603 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6604 .x(150)
6605 .y(50))
6606 .build()))
6607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6608 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6609 mWindow->consumeDragEvent(true, 150, 50);
6610 mSecondWindow->consumeDragEvent(false, 50, 50);
6611
6612 // drop to another window.
6613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6614 injectMotionEvent(mDispatcher,
6615 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6616 .buttonState(0)
6617 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6618 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6619 .x(150)
6620 .y(50))
6621 .build()))
6622 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6623 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6624 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6625 mWindow->assertNoEvents();
6626 mSecondWindow->assertNoEvents();
6627}
6628
Vishnu Nair062a8672021-09-03 16:07:44 -07006629class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6630
6631TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6632 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6633 sp<FakeWindowHandle> window =
6634 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006635 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006636 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6637 window->setFocusable(true);
6638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6639 setFocusedWindow(window);
6640 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6641
6642 // With the flag set, window should not get any input
6643 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6644 mDispatcher->notifyKey(&keyArgs);
6645 window->assertNoEvents();
6646
6647 NotifyMotionArgs motionArgs =
6648 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6649 ADISPLAY_ID_DEFAULT);
6650 mDispatcher->notifyMotion(&motionArgs);
6651 window->assertNoEvents();
6652
6653 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006654 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6656
6657 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6658 mDispatcher->notifyKey(&keyArgs);
6659 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6660
6661 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6662 ADISPLAY_ID_DEFAULT);
6663 mDispatcher->notifyMotion(&motionArgs);
6664 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6665 window->assertNoEvents();
6666}
6667
6668TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6669 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6670 std::make_shared<FakeApplicationHandle>();
6671 sp<FakeWindowHandle> obscuringWindow =
6672 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6673 ADISPLAY_ID_DEFAULT);
6674 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6675 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006676 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006677 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6678 sp<FakeWindowHandle> window =
6679 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006680 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006681 window->setOwnerInfo(222, 222);
6682 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6683 window->setFocusable(true);
6684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6685 setFocusedWindow(window);
6686 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6687
6688 // With the flag set, window should not get any input
6689 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6690 mDispatcher->notifyKey(&keyArgs);
6691 window->assertNoEvents();
6692
6693 NotifyMotionArgs motionArgs =
6694 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6695 ADISPLAY_ID_DEFAULT);
6696 mDispatcher->notifyMotion(&motionArgs);
6697 window->assertNoEvents();
6698
6699 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006700 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6702
6703 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6704 mDispatcher->notifyKey(&keyArgs);
6705 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6706
6707 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6708 ADISPLAY_ID_DEFAULT);
6709 mDispatcher->notifyMotion(&motionArgs);
6710 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6711 window->assertNoEvents();
6712}
6713
6714TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6715 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6716 std::make_shared<FakeApplicationHandle>();
6717 sp<FakeWindowHandle> obscuringWindow =
6718 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6719 ADISPLAY_ID_DEFAULT);
6720 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6721 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006722 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006723 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6724 sp<FakeWindowHandle> window =
6725 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006726 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006727 window->setOwnerInfo(222, 222);
6728 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6729 window->setFocusable(true);
6730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6731 setFocusedWindow(window);
6732 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6733
6734 // With the flag set, window should not get any input
6735 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6736 mDispatcher->notifyKey(&keyArgs);
6737 window->assertNoEvents();
6738
6739 NotifyMotionArgs motionArgs =
6740 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6741 ADISPLAY_ID_DEFAULT);
6742 mDispatcher->notifyMotion(&motionArgs);
6743 window->assertNoEvents();
6744
6745 // When the window is no longer obscured because it went on top, it should get input
6746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6747
6748 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6749 mDispatcher->notifyKey(&keyArgs);
6750 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6751
6752 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6753 ADISPLAY_ID_DEFAULT);
6754 mDispatcher->notifyMotion(&motionArgs);
6755 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6756 window->assertNoEvents();
6757}
6758
Antonio Kantekf16f2832021-09-28 04:39:20 +00006759class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6760protected:
6761 std::shared_ptr<FakeApplicationHandle> mApp;
6762 sp<FakeWindowHandle> mWindow;
6763 sp<FakeWindowHandle> mSecondWindow;
6764
6765 void SetUp() override {
6766 InputDispatcherTest::SetUp();
6767
6768 mApp = std::make_shared<FakeApplicationHandle>();
6769 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6770 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006771 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006772 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6773 mSecondWindow->setFocusable(true);
6774
6775 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006777 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006778
6779 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006780 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kanteka042c022022-07-06 16:51:07 -07006781 WINDOW_UID, true /*hasPermission*/, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006782 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6783 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6784 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006785 }
6786
Antonio Kantekea47acb2021-12-23 12:41:25 -08006787 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006788 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6789 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006790 mWindow->consumeTouchModeEvent(inTouchMode);
6791 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6792 }
6793};
6794
Antonio Kantek26defcf2022-02-08 01:12:27 +00006795TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006796 const WindowInfo& windowInfo = *mWindow->getInfo();
6797 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006798 windowInfo.ownerUid, false /*hasPermission*/);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006799}
6800
Antonio Kantek26defcf2022-02-08 01:12:27 +00006801TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6802 const WindowInfo& windowInfo = *mWindow->getInfo();
6803 int32_t ownerPid = windowInfo.ownerPid;
6804 int32_t ownerUid = windowInfo.ownerUid;
6805 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6806 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006807 ownerUid, false /*hasPermission*/,
6808 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006809 mWindow->assertNoEvents();
6810 mSecondWindow->assertNoEvents();
6811}
6812
6813TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6814 const WindowInfo& windowInfo = *mWindow->getInfo();
6815 int32_t ownerPid = windowInfo.ownerPid;
6816 int32_t ownerUid = windowInfo.ownerUid;
6817 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6818 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006819 true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006820}
6821
Antonio Kantekf16f2832021-09-28 04:39:20 +00006822TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006823 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006824 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6825 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006826 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006827 mWindow->assertNoEvents();
6828 mSecondWindow->assertNoEvents();
6829}
6830
Antonio Kantek48710e42022-03-24 14:19:30 -07006831TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6832 // Interact with the window first.
6833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6834 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6835 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6836
6837 // Then remove focus.
6838 mWindow->setFocusable(false);
6839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6840
6841 // Assert that caller can switch touch mode by owning one of the last interacted window.
6842 const WindowInfo& windowInfo = *mWindow->getInfo();
6843 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6844 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006845 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006846}
6847
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006848class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6849public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006850 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006851 std::shared_ptr<FakeApplicationHandle> application =
6852 std::make_shared<FakeApplicationHandle>();
6853 std::string name = "Fake Spy ";
6854 name += std::to_string(mSpyCount++);
6855 sp<FakeWindowHandle> spy =
6856 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006857 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006858 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006859 return spy;
6860 }
6861
6862 sp<FakeWindowHandle> createForeground() {
6863 std::shared_ptr<FakeApplicationHandle> application =
6864 std::make_shared<FakeApplicationHandle>();
6865 sp<FakeWindowHandle> window =
6866 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006867 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006868 return window;
6869 }
6870
6871private:
6872 int mSpyCount{0};
6873};
6874
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006875using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006876/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006877 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6878 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006879TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6880 ScopedSilentDeath _silentDeath;
6881
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006882 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006883 spy->setTrustedOverlay(false);
6884 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6885 ".* not a trusted overlay");
6886}
6887
6888/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006889 * Input injection into a display with a spy window but no foreground windows should succeed.
6890 */
6891TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006892 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6894
6895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6897 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6898 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6899}
6900
6901/**
6902 * Verify the order in which different input windows receive events. The touched foreground window
6903 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6904 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6905 * receive events before ones belows it.
6906 *
6907 * Here, we set up a scenario with four windows in the following Z order from the top:
6908 * spy1, spy2, window, spy3.
6909 * We then inject an event and verify that the foreground "window" receives it first, followed by
6910 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6911 * window.
6912 */
6913TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6914 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006915 auto spy1 = createSpy();
6916 auto spy2 = createSpy();
6917 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6919 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6920 const size_t numChannels = channels.size();
6921
Michael Wright8e9a8562022-02-09 13:44:29 +00006922 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006923 if (!epollFd.ok()) {
6924 FAIL() << "Failed to create epoll fd";
6925 }
6926
6927 for (size_t i = 0; i < numChannels; i++) {
6928 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6929 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6930 FAIL() << "Failed to add fd to epoll";
6931 }
6932 }
6933
6934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6935 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6936 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6937
6938 std::vector<size_t> eventOrder;
6939 std::vector<struct epoll_event> events(numChannels);
6940 for (;;) {
6941 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6942 (100ms).count());
6943 if (nFds < 0) {
6944 FAIL() << "Failed to call epoll_wait";
6945 }
6946 if (nFds == 0) {
6947 break; // epoll_wait timed out
6948 }
6949 for (int i = 0; i < nFds; i++) {
6950 ASSERT_EQ(EPOLLIN, events[i].events);
6951 eventOrder.push_back(events[i].data.u64);
6952 channels[i]->consumeMotionDown();
6953 }
6954 }
6955
6956 // Verify the order in which the events were received.
6957 EXPECT_EQ(3u, eventOrder.size());
6958 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6959 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6960 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6961}
6962
6963/**
6964 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6965 */
6966TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6967 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006968 auto spy = createSpy();
6969 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6971
6972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6973 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6975 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6976 spy->assertNoEvents();
6977}
6978
6979/**
6980 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6981 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6982 * to the window.
6983 */
6984TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6985 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006986 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006987 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6989
6990 // Inject an event outside the spy window's touchable region.
6991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6992 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6994 window->consumeMotionDown();
6995 spy->assertNoEvents();
6996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6997 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6998 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6999 window->consumeMotionUp();
7000 spy->assertNoEvents();
7001
7002 // Inject an event inside the spy window's touchable region.
7003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7004 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7005 {5, 10}))
7006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7007 window->consumeMotionDown();
7008 spy->consumeMotionDown();
7009}
7010
7011/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007012 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007013 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007014 */
7015TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7016 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007017 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007018 auto spy = createSpy();
7019 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007020 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007021 spy->setFrame(Rect{0, 0, 20, 20});
7022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7023
7024 // Inject an event outside the spy window's frame and touchable region.
7025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007026 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7027 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007028 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7029 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007030 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007031}
7032
7033/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007034 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7035 * pointers that are down within its bounds.
7036 */
7037TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7038 auto windowLeft = createForeground();
7039 windowLeft->setFrame({0, 0, 100, 200});
7040 auto windowRight = createForeground();
7041 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007042 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007043 spy->setFrame({0, 0, 200, 200});
7044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7045
7046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7047 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7048 {50, 50}))
7049 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7050 windowLeft->consumeMotionDown();
7051 spy->consumeMotionDown();
7052
7053 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007054 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007055 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7056 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7057 .pointer(
7058 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7059 .build();
7060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7061 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7062 InputEventInjectionSync::WAIT_FOR_RESULT))
7063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7064 windowRight->consumeMotionDown();
7065 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7066}
7067
7068/**
7069 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7070 * the spy should receive the second pointer with ACTION_DOWN.
7071 */
7072TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7073 auto window = createForeground();
7074 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007075 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007076 spyRight->setFrame({100, 0, 200, 200});
7077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7078
7079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7080 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7081 {50, 50}))
7082 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7083 window->consumeMotionDown();
7084 spyRight->assertNoEvents();
7085
7086 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007087 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007088 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7089 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7090 .pointer(
7091 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7092 .build();
7093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7094 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7095 InputEventInjectionSync::WAIT_FOR_RESULT))
7096 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7097 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7098 spyRight->consumeMotionDown();
7099}
7100
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007101/**
7102 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7103 * windows should be allowed to control split touch.
7104 */
7105TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007106 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007107 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007108 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007109 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007110
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007111 auto window = createForeground();
7112 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007113
7114 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7115
7116 // First finger down, no window touched.
7117 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7118 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7119 {100, 200}))
7120 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7121 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7122 window->assertNoEvents();
7123
7124 // Second finger down on window, the window should receive touch down.
7125 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007126 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007127 .displayId(ADISPLAY_ID_DEFAULT)
7128 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7129 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7130 .x(100)
7131 .y(200))
7132 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7133 .build();
7134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7135 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7136 InputEventInjectionSync::WAIT_FOR_RESULT))
7137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7138
7139 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7140 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7141}
7142
7143/**
7144 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7145 * do not receive key events.
7146 */
7147TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007148 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007149 spy->setFocusable(false);
7150
7151 auto window = createForeground();
7152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7153 setFocusedWindow(window);
7154 window->consumeFocusEvent(true);
7155
7156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7157 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7158 window->consumeKeyDown(ADISPLAY_ID_NONE);
7159
7160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7161 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7162 window->consumeKeyUp(ADISPLAY_ID_NONE);
7163
7164 spy->assertNoEvents();
7165}
7166
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007167using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7168
7169/**
7170 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7171 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7172 */
7173TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7174 auto window = createForeground();
7175 auto spy1 = createSpy();
7176 auto spy2 = createSpy();
7177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7178
7179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7180 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7181 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7182 window->consumeMotionDown();
7183 spy1->consumeMotionDown();
7184 spy2->consumeMotionDown();
7185
7186 // Pilfer pointers from the second spy window.
7187 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7188 spy2->assertNoEvents();
7189 spy1->consumeMotionCancel();
7190 window->consumeMotionCancel();
7191
7192 // The rest of the gesture should only be sent to the second spy window.
7193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7194 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7195 ADISPLAY_ID_DEFAULT))
7196 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7197 spy2->consumeMotionMove();
7198 spy1->assertNoEvents();
7199 window->assertNoEvents();
7200}
7201
7202/**
7203 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7204 * in the middle of the gesture.
7205 */
7206TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7207 auto window = createForeground();
7208 auto spy = createSpy();
7209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7210
7211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7212 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7213 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7214 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7215 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7216
7217 window->releaseChannel();
7218
7219 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7220
7221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7222 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7223 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7224 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7225}
7226
7227/**
7228 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7229 * the spy, but not to any other windows.
7230 */
7231TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7232 auto spy = createSpy();
7233 auto window = createForeground();
7234
7235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7236
7237 // First finger down on the window and the spy.
7238 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7239 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7240 {100, 200}))
7241 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7242 spy->consumeMotionDown();
7243 window->consumeMotionDown();
7244
7245 // Spy window pilfers the pointers.
7246 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7247 window->consumeMotionCancel();
7248
7249 // Second finger down on the window and spy, but the window should not receive the pointer down.
7250 const MotionEvent secondFingerDownEvent =
7251 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7252 .displayId(ADISPLAY_ID_DEFAULT)
7253 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7254 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7255 .x(100)
7256 .y(200))
7257 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7258 .build();
7259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7260 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7261 InputEventInjectionSync::WAIT_FOR_RESULT))
7262 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7263
7264 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7265
7266 // Third finger goes down outside all windows, so injection should fail.
7267 const MotionEvent thirdFingerDownEvent =
7268 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7269 .displayId(ADISPLAY_ID_DEFAULT)
7270 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7271 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7272 .x(100)
7273 .y(200))
7274 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7275 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7276 .build();
7277 ASSERT_EQ(InputEventInjectionResult::FAILED,
7278 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7279 InputEventInjectionSync::WAIT_FOR_RESULT))
7280 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7281
7282 spy->assertNoEvents();
7283 window->assertNoEvents();
7284}
7285
7286/**
7287 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7288 */
7289TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7290 auto spy = createSpy();
7291 spy->setFrame(Rect(0, 0, 100, 100));
7292 auto window = createForeground();
7293 window->setFrame(Rect(0, 0, 200, 200));
7294
7295 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7296
7297 // First finger down on the window only
7298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7299 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7300 {150, 150}))
7301 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7302 window->consumeMotionDown();
7303
7304 // Second finger down on the spy and window
7305 const MotionEvent secondFingerDownEvent =
7306 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7307 .displayId(ADISPLAY_ID_DEFAULT)
7308 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7309 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7310 .x(150)
7311 .y(150))
7312 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7313 .build();
7314 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7315 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7316 InputEventInjectionSync::WAIT_FOR_RESULT))
7317 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7318 spy->consumeMotionDown();
7319 window->consumeMotionPointerDown(1);
7320
7321 // Third finger down on the spy and window
7322 const MotionEvent thirdFingerDownEvent =
7323 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7324 .displayId(ADISPLAY_ID_DEFAULT)
7325 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7326 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7327 .x(150)
7328 .y(150))
7329 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7330 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7331 .build();
7332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7333 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7334 InputEventInjectionSync::WAIT_FOR_RESULT))
7335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7336 spy->consumeMotionPointerDown(1);
7337 window->consumeMotionPointerDown(2);
7338
7339 // Spy window pilfers the pointers.
7340 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7341 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7342 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7343
7344 spy->assertNoEvents();
7345 window->assertNoEvents();
7346}
7347
7348/**
7349 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7350 * other windows should be canceled. If this results in the cancellation of all pointers for some
7351 * window, then that window should receive ACTION_CANCEL.
7352 */
7353TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7354 auto spy = createSpy();
7355 spy->setFrame(Rect(0, 0, 100, 100));
7356 auto window = createForeground();
7357 window->setFrame(Rect(0, 0, 200, 200));
7358
7359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7360
7361 // First finger down on both spy and window
7362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7363 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7364 {10, 10}))
7365 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7366 window->consumeMotionDown();
7367 spy->consumeMotionDown();
7368
7369 // Second finger down on the spy and window
7370 const MotionEvent secondFingerDownEvent =
7371 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7372 .displayId(ADISPLAY_ID_DEFAULT)
7373 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7374 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7375 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7376 .build();
7377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7378 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7379 InputEventInjectionSync::WAIT_FOR_RESULT))
7380 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7381 spy->consumeMotionPointerDown(1);
7382 window->consumeMotionPointerDown(1);
7383
7384 // Spy window pilfers the pointers.
7385 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7386 window->consumeMotionCancel();
7387
7388 spy->assertNoEvents();
7389 window->assertNoEvents();
7390}
7391
7392/**
7393 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7394 * be sent to other windows
7395 */
7396TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7397 auto spy = createSpy();
7398 spy->setFrame(Rect(0, 0, 100, 100));
7399 auto window = createForeground();
7400 window->setFrame(Rect(0, 0, 200, 200));
7401
7402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7403
7404 // First finger down on both window and spy
7405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7406 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7407 {10, 10}))
7408 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7409 window->consumeMotionDown();
7410 spy->consumeMotionDown();
7411
7412 // Spy window pilfers the pointers.
7413 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7414 window->consumeMotionCancel();
7415
7416 // Second finger down on the window only
7417 const MotionEvent secondFingerDownEvent =
7418 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7419 .displayId(ADISPLAY_ID_DEFAULT)
7420 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7421 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7422 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7423 .x(150)
7424 .y(150))
7425 .build();
7426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7427 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7428 InputEventInjectionSync::WAIT_FOR_RESULT))
7429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7430 window->consumeMotionDown();
7431 window->assertNoEvents();
7432
7433 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7434 spy->consumeMotionMove();
7435 spy->assertNoEvents();
7436}
7437
Prabir Pradhand65552b2021-10-07 11:23:50 -07007438class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7439public:
7440 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7441 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7442 std::make_shared<FakeApplicationHandle>();
7443 sp<FakeWindowHandle> overlay =
7444 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
7445 ADISPLAY_ID_DEFAULT);
7446 overlay->setFocusable(false);
7447 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007448 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007449 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007450 overlay->setTrustedOverlay(true);
7451
7452 std::shared_ptr<FakeApplicationHandle> application =
7453 std::make_shared<FakeApplicationHandle>();
7454 sp<FakeWindowHandle> window =
7455 new FakeWindowHandle(application, mDispatcher, "Application window",
7456 ADISPLAY_ID_DEFAULT);
7457 window->setFocusable(true);
7458 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007459
7460 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7462 setFocusedWindow(window);
7463 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7464 return {std::move(overlay), std::move(window)};
7465 }
7466
7467 void sendFingerEvent(int32_t action) {
7468 NotifyMotionArgs motionArgs =
7469 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7470 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7471 mDispatcher->notifyMotion(&motionArgs);
7472 }
7473
7474 void sendStylusEvent(int32_t action) {
7475 NotifyMotionArgs motionArgs =
7476 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7477 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7478 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7479 mDispatcher->notifyMotion(&motionArgs);
7480 }
7481};
7482
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007483using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7484
7485TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7486 ScopedSilentDeath _silentDeath;
7487
Prabir Pradhand65552b2021-10-07 11:23:50 -07007488 auto [overlay, window] = setupStylusOverlayScenario();
7489 overlay->setTrustedOverlay(false);
7490 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7491 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7492 ".* not a trusted overlay");
7493}
7494
7495TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7496 auto [overlay, window] = setupStylusOverlayScenario();
7497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7498
7499 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7500 overlay->consumeMotionDown();
7501 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7502 overlay->consumeMotionUp();
7503
7504 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7505 window->consumeMotionDown();
7506 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7507 window->consumeMotionUp();
7508
7509 overlay->assertNoEvents();
7510 window->assertNoEvents();
7511}
7512
7513TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7514 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007515 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7517
7518 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7519 overlay->consumeMotionDown();
7520 window->consumeMotionDown();
7521 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7522 overlay->consumeMotionUp();
7523 window->consumeMotionUp();
7524
7525 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7526 window->consumeMotionDown();
7527 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7528 window->consumeMotionUp();
7529
7530 overlay->assertNoEvents();
7531 window->assertNoEvents();
7532}
7533
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007534/**
7535 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7536 * The scenario is as follows:
7537 * - The stylus interceptor overlay is configured as a spy window.
7538 * - The stylus interceptor spy receives the start of a new stylus gesture.
7539 * - It pilfers pointers and then configures itself to no longer be a spy.
7540 * - The stylus interceptor continues to receive the rest of the gesture.
7541 */
7542TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7543 auto [overlay, window] = setupStylusOverlayScenario();
7544 overlay->setSpy(true);
7545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7546
7547 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7548 overlay->consumeMotionDown();
7549 window->consumeMotionDown();
7550
7551 // The interceptor pilfers the pointers.
7552 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7553 window->consumeMotionCancel();
7554
7555 // The interceptor configures itself so that it is no longer a spy.
7556 overlay->setSpy(false);
7557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7558
7559 // It continues to receive the rest of the stylus gesture.
7560 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7561 overlay->consumeMotionMove();
7562 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7563 overlay->consumeMotionUp();
7564
7565 window->assertNoEvents();
7566}
7567
Prabir Pradhan5735a322022-04-11 17:23:34 +00007568struct User {
7569 int32_t mPid;
7570 int32_t mUid;
7571 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7572 std::unique_ptr<InputDispatcher>& mDispatcher;
7573
7574 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7575 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7576
7577 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7578 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7579 ADISPLAY_ID_DEFAULT, {100, 200},
7580 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7581 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7582 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7583 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7584 }
7585
7586 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7587 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7588 InputEventInjectionSync::WAIT_FOR_RESULT,
7589 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7590 mPolicyFlags);
7591 }
7592
7593 sp<FakeWindowHandle> createWindow() const {
7594 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7595 std::make_shared<FakeApplicationHandle>();
7596 sp<FakeWindowHandle> window = new FakeWindowHandle(overlayApplication, mDispatcher,
7597 "Owned Window", ADISPLAY_ID_DEFAULT);
7598 window->setOwnerInfo(mPid, mUid);
7599 return window;
7600 }
7601};
7602
7603using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7604
7605TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7606 auto owner = User(mDispatcher, 10, 11);
7607 auto window = owner.createWindow();
7608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7609
7610 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7611 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7612 window->consumeMotionDown();
7613
7614 setFocusedWindow(window);
7615 window->consumeFocusEvent(true);
7616
7617 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7618 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7619 window->consumeKeyDown(ADISPLAY_ID_NONE);
7620}
7621
7622TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7623 auto owner = User(mDispatcher, 10, 11);
7624 auto window = owner.createWindow();
7625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7626
7627 auto rando = User(mDispatcher, 20, 21);
7628 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7629 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7630
7631 setFocusedWindow(window);
7632 window->consumeFocusEvent(true);
7633
7634 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7635 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7636 window->assertNoEvents();
7637}
7638
7639TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7640 auto owner = User(mDispatcher, 10, 11);
7641 auto window = owner.createWindow();
7642 auto spy = owner.createWindow();
7643 spy->setSpy(true);
7644 spy->setTrustedOverlay(true);
7645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7646
7647 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7648 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7649 spy->consumeMotionDown();
7650 window->consumeMotionDown();
7651}
7652
7653TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7654 auto owner = User(mDispatcher, 10, 11);
7655 auto window = owner.createWindow();
7656
7657 auto rando = User(mDispatcher, 20, 21);
7658 auto randosSpy = rando.createWindow();
7659 randosSpy->setSpy(true);
7660 randosSpy->setTrustedOverlay(true);
7661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7662
7663 // The event is targeted at owner's window, so injection should succeed, but the spy should
7664 // not receive the event.
7665 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7666 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7667 randosSpy->assertNoEvents();
7668 window->consumeMotionDown();
7669}
7670
7671TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7672 auto owner = User(mDispatcher, 10, 11);
7673 auto window = owner.createWindow();
7674
7675 auto rando = User(mDispatcher, 20, 21);
7676 auto randosSpy = rando.createWindow();
7677 randosSpy->setSpy(true);
7678 randosSpy->setTrustedOverlay(true);
7679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7680
7681 // A user that has injection permission can inject into any window.
7682 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7683 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7684 ADISPLAY_ID_DEFAULT));
7685 randosSpy->consumeMotionDown();
7686 window->consumeMotionDown();
7687
7688 setFocusedWindow(randosSpy);
7689 randosSpy->consumeFocusEvent(true);
7690
7691 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7692 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7693 window->assertNoEvents();
7694}
7695
7696TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7697 auto owner = User(mDispatcher, 10, 11);
7698 auto window = owner.createWindow();
7699
7700 auto rando = User(mDispatcher, 20, 21);
7701 auto randosWindow = rando.createWindow();
7702 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7703 randosWindow->setWatchOutsideTouch(true);
7704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7705
7706 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7707 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7708 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7709 window->consumeMotionDown();
7710 randosWindow->consumeMotionOutside();
7711}
7712
Garfield Tane84e6f92019-08-29 17:28:41 -07007713} // namespace android::inputdispatcher