blob: 2c64271ccaa1a1cce8626e36faaf0b7f80fe2f1f [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>
Garfield Tan1c7bc862020-01-28 13:24:04 -080020#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070021#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070022#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080023#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100024#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026
Garfield Tan1c7bc862020-01-28 13:24:04 -080027#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070028#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080029#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080030#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080031
Garfield Tan1c7bc862020-01-28 13:24:04 -080032using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050033using android::gui::FocusRequest;
34using android::gui::TouchOcclusionMode;
35using android::gui::WindowInfo;
36using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080037using android::os::InputEventInjectionResult;
38using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010039using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080040
Garfield Tane84e6f92019-08-29 17:28:41 -070041namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080042
43// An arbitrary time value.
44static const nsecs_t ARBITRARY_TIME = 1234;
45
46// An arbitrary device id.
47static const int32_t DEVICE_ID = 1;
48
Jeff Brownf086ddb2014-02-11 14:28:48 -080049// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000050static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
51static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053// An arbitrary injector pid / uid pair that has permission to inject events.
54static const int32_t INJECTOR_PID = 999;
55static const int32_t INJECTOR_UID = 1001;
56
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000057// An arbitrary pid of the gesture monitor window
58static constexpr int32_t MONITOR_PID = 2001;
59
chaviwd1c23182019-12-20 18:44:56 -080060struct PointF {
61 float x;
62 float y;
63};
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Gang Wang342c9272020-01-13 13:15:04 -050065/**
66 * Return a DOWN key event with KEYCODE_A.
67 */
68static KeyEvent getTestKeyEvent() {
69 KeyEvent event;
70
Garfield Tanfbe732e2020-01-24 11:26:14 -080071 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
72 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
73 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050074 return event;
75}
76
Siarhei Vishniakouca205502021-07-16 21:31:58 +000077static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
78 ASSERT_EQ(expectedAction, receivedAction)
79 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
80 << MotionEvent::actionToString(receivedAction);
81}
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// --- FakeInputDispatcherPolicy ---
84
85class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
86 InputDispatcherConfiguration mConfig;
87
88protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100089 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100092 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080093
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080094 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070095 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
96 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
97 EXPECT_EQ(event.getDisplayId(), args.displayId);
98
99 const auto& keyEvent = static_cast<const KeyEvent&>(event);
100 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
101 EXPECT_EQ(keyEvent.getAction(), args.action);
102 });
Jackal Guof9696682018-10-05 12:23:23 +0800103 }
104
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700105 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
106 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
107 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
108 EXPECT_EQ(event.getDisplayId(), args.displayId);
109
110 const auto& motionEvent = static_cast<const MotionEvent&>(event);
111 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
112 EXPECT_EQ(motionEvent.getAction(), args.action);
113 EXPECT_EQ(motionEvent.getX(0), point.x);
114 EXPECT_EQ(motionEvent.getY(0), point.y);
115 EXPECT_EQ(motionEvent.getRawX(0), point.x);
116 EXPECT_EQ(motionEvent.getRawY(0), point.y);
117 });
Jackal Guof9696682018-10-05 12:23:23 +0800118 }
119
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700120 void assertFilterInputEventWasNotCalled() {
121 std::scoped_lock lock(mLock);
122 ASSERT_EQ(nullptr, mFilteredEvent);
123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800125 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700126 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800127 ASSERT_TRUE(mConfigurationChangedTime)
128 << "Timed out waiting for configuration changed call";
129 ASSERT_EQ(*mConfigurationChangedTime, when);
130 mConfigurationChangedTime = std::nullopt;
131 }
132
133 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700134 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800135 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800136 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
138 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
139 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
140 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
141 mLastNotifySwitch = std::nullopt;
142 }
143
chaviwfd6d3512019-03-25 13:23:49 -0700144 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700145 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800146 ASSERT_EQ(touchedToken, mOnPointerDownToken);
147 mOnPointerDownToken.clear();
148 }
149
150 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700151 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800152 ASSERT_TRUE(mOnPointerDownToken == nullptr)
153 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700154 }
155
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700156 // This function must be called soon after the expected ANR timer starts,
157 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500158 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700159 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500160 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
161 std::shared_ptr<InputApplicationHandle> application;
162 { // acquire lock
163 std::unique_lock lock(mLock);
164 android::base::ScopedLockAssertion assumeLocked(mLock);
165 ASSERT_NO_FATAL_FAILURE(
166 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
167 } // release lock
168 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700169 }
170
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000171 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
172 const sp<IBinder>& expectedConnectionToken) {
173 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500174 ASSERT_EQ(expectedConnectionToken, connectionToken);
175 }
176
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000177 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
178 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500179 ASSERT_EQ(expectedConnectionToken, connectionToken);
180 }
181
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000182 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
183 int32_t pid = getUnresponsiveMonitorPid(timeout);
184 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500185 }
186
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000187 void assertNotifyMonitorResponsiveWasCalled() {
188 int32_t pid = getResponsiveMonitorPid();
189 ASSERT_EQ(MONITOR_PID, pid);
190 }
191
192 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500193 std::unique_lock lock(mLock);
194 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000195 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
196 }
197
198 sp<IBinder> getResponsiveWindowToken() {
199 std::unique_lock lock(mLock);
200 android::base::ScopedLockAssertion assumeLocked(mLock);
201 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
202 }
203
204 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
205 std::unique_lock lock(mLock);
206 android::base::ScopedLockAssertion assumeLocked(mLock);
207 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
208 }
209
210 int32_t getResponsiveMonitorPid() {
211 std::unique_lock lock(mLock);
212 android::base::ScopedLockAssertion assumeLocked(mLock);
213 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500214 }
215
216 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
217 // for a specific container to become non-empty. When the container is non-empty, return the
218 // first entry from the container and erase it.
219 template <class T>
220 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
221 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700222 // If there is an ANR, Dispatcher won't be idle because there are still events
223 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
224 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500225 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
226 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800227 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
228 const std::chrono::time_point start = std::chrono::steady_clock::now();
229 std::optional<T> token =
230 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
231 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500232 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000233 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700234 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800235
236 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700237 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
238 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700239 if (std::chrono::abs(timeout - waited) > 100ms) {
240 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
241 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
242 << "ms, but waited "
243 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
244 << "ms instead";
245 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800246 return *token;
247 }
248
249 template <class T>
250 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
251 std::queue<T>& storage,
252 std::unique_lock<std::mutex>& lock,
253 std::condition_variable& condition)
254 REQUIRES(mLock) {
255 condition.wait_for(lock, timeout,
256 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
257 if (storage.empty()) {
258 ADD_FAILURE() << "Did not receive the expected callback";
259 return std::nullopt;
260 }
261 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500262 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800263 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700264 }
265
266 void assertNotifyAnrWasNotCalled() {
267 std::scoped_lock lock(mLock);
268 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000269 ASSERT_TRUE(mAnrWindowTokens.empty());
270 ASSERT_TRUE(mAnrMonitorPids.empty());
271 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500272 << "ANR was not called, but please also consume the 'connection is responsive' "
273 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000274 ASSERT_TRUE(mResponsiveMonitorPids.empty())
275 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
276 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700277 }
278
Garfield Tan1c7bc862020-01-28 13:24:04 -0800279 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
280 mConfig.keyRepeatTimeout = timeout;
281 mConfig.keyRepeatDelay = delay;
282 }
283
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000284 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800285 std::unique_lock lock(mLock);
286 base::ScopedLockAssertion assumeLocked(mLock);
287
288 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
289 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000290 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800291 enabled;
292 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000293 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
294 << ") to be called.";
295 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800296 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000297 auto request = *mPointerCaptureRequest;
298 mPointerCaptureRequest.reset();
299 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800300 }
301
302 void assertSetPointerCaptureNotCalled() {
303 std::unique_lock lock(mLock);
304 base::ScopedLockAssertion assumeLocked(mLock);
305
306 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000307 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800308 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000309 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800310 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000311 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 }
313
arthurhungf452d0b2021-01-06 00:19:52 +0800314 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
315 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800316 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800317 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800318 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800319 }
320
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800321 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
322 std::unique_lock lock(mLock);
323 base::ScopedLockAssertion assumeLocked(mLock);
324 std::optional<sp<IBinder>> receivedToken =
325 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
326 mNotifyInputChannelBroken);
327 ASSERT_TRUE(receivedToken.has_value());
328 ASSERT_EQ(token, *receivedToken);
329 }
330
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700332 std::mutex mLock;
333 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
334 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
335 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
336 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800337
Prabir Pradhan99987712020-11-10 18:43:05 -0800338 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000339
340 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800341
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700342 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700343 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000344 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
345 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
346 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
347 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700348 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800349 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
350 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700351
arthurhungf452d0b2021-01-06 00:19:52 +0800352 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800353 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800354
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600355 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700356 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800357 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358 }
359
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000360 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700361 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000362 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700363 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500364 }
365
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000366 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500367 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000368 mAnrMonitorPids.push(pid);
369 mNotifyAnr.notify_all();
370 }
371
372 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
373 std::scoped_lock lock(mLock);
374 mResponsiveWindowTokens.push(connectionToken);
375 mNotifyAnr.notify_all();
376 }
377
378 void notifyMonitorResponsive(int32_t pid) override {
379 std::scoped_lock lock(mLock);
380 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500381 mNotifyAnr.notify_all();
382 }
383
384 void notifyNoFocusedWindowAnr(
385 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
386 std::scoped_lock lock(mLock);
387 mAnrApplications.push(applicationHandle);
388 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389 }
390
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800391 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
392 std::scoped_lock lock(mLock);
393 mBrokenInputChannels.push(connectionToken);
394 mNotifyInputChannelBroken.notify_all();
395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600397 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700398
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600399 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700400 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
401 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
402 const std::vector<float>& values) override {}
403
404 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
405 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000406
Chris Yefb552902021-02-03 17:18:37 -0800407 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
408
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600409 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 *outConfig = mConfig;
411 }
412
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600413 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700414 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800415 switch (inputEvent->getType()) {
416 case AINPUT_EVENT_TYPE_KEY: {
417 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800418 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800419 break;
420 }
421
422 case AINPUT_EVENT_TYPE_MOTION: {
423 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800424 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800425 break;
426 }
427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 return true;
429 }
430
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600431 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600433 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600435 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 return 0;
437 }
438
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600439 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 return false;
441 }
442
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600443 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
444 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700445 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800446 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
447 * essentially a passthrough for notifySwitch.
448 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800449 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
Sean Stoutb4e0a592021-02-23 07:34:53 -0800452 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800454 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
455 return pid == INJECTOR_PID && uid == INJECTOR_UID;
456 }
Jackal Guof9696682018-10-05 12:23:23 +0800457
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600458 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700459 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700460 mOnPointerDownToken = newToken;
461 }
462
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000463 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800464 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000465 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800466 mPointerCaptureChangedCondition.notify_all();
467 }
468
arthurhungf452d0b2021-01-06 00:19:52 +0800469 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
470 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800471 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800472 mDropTargetWindowToken = token;
473 }
474
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700475 void assertFilterInputEventWasCalledInternal(
476 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700477 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800478 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700479 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800480 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482};
483
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484// --- InputDispatcherTest ---
485
486class InputDispatcherTest : public testing::Test {
487protected:
488 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700489 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000491 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700493 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800494 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000495 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700496 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 }
498
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000499 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700500 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700502 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700504
505 /**
506 * Used for debugging when writing the test
507 */
508 void dumpDispatcherState() {
509 std::string dump;
510 mDispatcher->dump(dump);
511 std::stringstream ss(dump);
512 std::string to;
513
514 while (std::getline(ss, to, '\n')) {
515 ALOGE("%s", to.c_str());
516 }
517 }
Vishnu Nair958da932020-08-21 17:12:37 -0700518
chaviw3277faf2021-05-19 16:45:23 -0500519 void setFocusedWindow(const sp<WindowInfoHandle>& window,
520 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700521 FocusRequest request;
522 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000523 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700524 if (focusedWindow) {
525 request.focusedToken = focusedWindow->getToken();
526 }
527 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
528 request.displayId = window->getInfo()->displayId;
529 mDispatcher->setFocusedWindow(request);
530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531};
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
534 KeyEvent event;
535
536 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800537 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
538 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600539 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
540 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800541 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700542 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800543 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 << "Should reject key events with undefined action.";
545
546 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800547 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
548 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600549 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800550 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700551 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 << "Should reject key events with ACTION_MULTIPLE.";
554}
555
556TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
557 MotionEvent event;
558 PointerProperties pointerProperties[MAX_POINTERS + 1];
559 PointerCoords pointerCoords[MAX_POINTERS + 1];
560 for (int i = 0; i <= MAX_POINTERS; i++) {
561 pointerProperties[i].clear();
562 pointerProperties[i].id = i;
563 pointerCoords[i].clear();
564 }
565
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800566 // Some constants commonly used below
567 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
568 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
569 constexpr int32_t metaState = AMETA_NONE;
570 constexpr MotionClassification classification = MotionClassification::NONE;
571
chaviw9eaa22c2020-07-01 16:21:27 -0700572 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800574 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700575 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
576 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700577 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
578 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700579 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800580 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700581 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800582 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 << "Should reject motion events with undefined action.";
584
585 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800586 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700587 AMOTION_EVENT_ACTION_POINTER_DOWN |
588 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700589 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
590 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700591 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500592 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800593 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700594 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 << "Should reject motion events with pointer down index too large.";
597
Garfield Tanfbe732e2020-01-24 11:26:14 -0800598 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 AMOTION_EVENT_ACTION_POINTER_DOWN |
600 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700601 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
602 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700606 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with pointer down index too small.";
609
610 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700612 AMOTION_EVENT_ACTION_POINTER_UP |
613 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700614 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
615 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700616 identityTransform, ARBITRARY_TIME, 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,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700619 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800620 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 << "Should reject motion events with pointer up 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_UP |
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,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700631 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800632 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 << "Should reject motion events with pointer up index too small.";
634
635 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800636 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
637 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700638 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700639 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
640 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800642 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700643 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800644 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 << "Should reject motion events with 0 pointers.";
646
Garfield Tanfbe732e2020-01-24 11:26:14 -0800647 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
648 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700649 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700650 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
651 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700652 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800653 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700654 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800655 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 << "Should reject motion events with more than MAX_POINTERS pointers.";
657
658 // Rejects motion events with invalid pointer ids.
659 pointerProperties[0].id = -1;
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*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700667 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800668 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 << "Should reject motion events with pointer ids less than 0.";
670
671 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800672 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
673 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700674 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700675 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
676 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700677 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800678 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700679 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800680 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
682
683 // Rejects motion events with duplicate pointer ids.
684 pointerProperties[0].id = 1;
685 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800686 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
687 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700688 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700689 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
690 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700691 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800692 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700693 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800694 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 << "Should reject motion events with duplicate pointer ids.";
696}
697
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800698/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
699
700TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
701 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800702 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800703 mDispatcher->notifyConfigurationChanged(&args);
704 ASSERT_TRUE(mDispatcher->waitForIdle());
705
706 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
707}
708
709TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800710 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
711 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800712 mDispatcher->notifySwitch(&args);
713
714 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
715 args.policyFlags |= POLICY_FLAG_TRUSTED;
716 mFakePolicy->assertNotifySwitchWasCalled(args);
717}
718
Arthur Hungb92218b2018-08-14 12:00:21 +0800719// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700720static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700721// Default input dispatching timeout if there is no focused application or paused window
722// from which to determine an appropriate dispatching timeout.
723static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
724 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
725 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800726
727class FakeApplicationHandle : public InputApplicationHandle {
728public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700729 FakeApplicationHandle() {
730 mInfo.name = "Fake Application";
731 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500732 mInfo.dispatchingTimeoutMillis =
733 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700734 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800735 virtual ~FakeApplicationHandle() {}
736
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000737 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700738
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500739 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
740 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700741 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800742};
743
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800744class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800745public:
Garfield Tan15601662020-09-22 15:32:38 -0700746 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800747 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700748 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800749 }
750
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800751 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 InputEvent* event;
753 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
754 if (!consumeSeq) {
755 return nullptr;
756 }
757 finishEvent(*consumeSeq);
758 return event;
759 }
760
761 /**
762 * Receive an event without acknowledging it.
763 * Return the sequence number that could later be used to send finished signal.
764 */
765 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800766 uint32_t consumeSeq;
767 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800768
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800769 std::chrono::time_point start = std::chrono::steady_clock::now();
770 status_t status = WOULD_BLOCK;
771 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800772 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800773 &event);
774 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
775 if (elapsed > 100ms) {
776 break;
777 }
778 }
779
780 if (status == WOULD_BLOCK) {
781 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700782 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800783 }
784
785 if (status != OK) {
786 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700787 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800788 }
789 if (event == nullptr) {
790 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700791 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700793 if (outEvent != nullptr) {
794 *outEvent = event;
795 }
796 return consumeSeq;
797 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800798
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700799 /**
800 * To be used together with "receiveEvent" to complete the consumption of an event.
801 */
802 void finishEvent(uint32_t consumeSeq) {
803 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
804 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800805 }
806
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000807 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
808 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
809 ASSERT_EQ(OK, status);
810 }
811
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000812 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
813 std::optional<int32_t> expectedDisplayId,
814 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815 InputEvent* event = consume();
816
817 ASSERT_NE(nullptr, event) << mName.c_str()
818 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800819 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700820 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800821 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800822
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000823 if (expectedDisplayId.has_value()) {
824 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
825 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826
Tiger Huang8664f8c2018-10-11 19:14:35 +0800827 switch (expectedEventType) {
828 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800829 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
830 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000831 if (expectedFlags.has_value()) {
832 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
833 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800834 break;
835 }
836 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800837 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000838 assertMotionAction(expectedAction, motionEvent.getAction());
839
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000840 if (expectedFlags.has_value()) {
841 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
842 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800843 break;
844 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100845 case AINPUT_EVENT_TYPE_FOCUS: {
846 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
847 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800848 case AINPUT_EVENT_TYPE_CAPTURE: {
849 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
850 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000851 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
852 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
853 }
arthurhungb89ccb02020-12-30 16:19:01 +0800854 case AINPUT_EVENT_TYPE_DRAG: {
855 FAIL() << "Use 'consumeDragEvent' for DRAG events";
856 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800857 default: {
858 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
859 }
860 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800861 }
862
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100863 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
864 InputEvent* event = consume();
865 ASSERT_NE(nullptr, event) << mName.c_str()
866 << ": consumer should have returned non-NULL event.";
867 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
868 << "Got " << inputEventTypeToString(event->getType())
869 << " event instead of FOCUS event";
870
871 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
872 << mName.c_str() << ": event displayId should always be NONE.";
873
874 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
875 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100876 }
877
Prabir Pradhan99987712020-11-10 18:43:05 -0800878 void consumeCaptureEvent(bool hasCapture) {
879 const InputEvent* event = consume();
880 ASSERT_NE(nullptr, event) << mName.c_str()
881 << ": consumer should have returned non-NULL event.";
882 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
883 << "Got " << inputEventTypeToString(event->getType())
884 << " event instead of CAPTURE event";
885
886 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
887 << mName.c_str() << ": event displayId should always be NONE.";
888
889 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
890 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
891 }
892
arthurhungb89ccb02020-12-30 16:19:01 +0800893 void consumeDragEvent(bool isExiting, float x, float y) {
894 const InputEvent* event = consume();
895 ASSERT_NE(nullptr, event) << mName.c_str()
896 << ": consumer should have returned non-NULL event.";
897 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
898 << "Got " << inputEventTypeToString(event->getType())
899 << " event instead of DRAG event";
900
901 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
902 << mName.c_str() << ": event displayId should always be NONE.";
903
904 const auto& dragEvent = static_cast<const DragEvent&>(*event);
905 EXPECT_EQ(isExiting, dragEvent.isExiting());
906 EXPECT_EQ(x, dragEvent.getX());
907 EXPECT_EQ(y, dragEvent.getY());
908 }
909
Antonio Kantekf16f2832021-09-28 04:39:20 +0000910 void consumeTouchModeEvent(bool inTouchMode) {
911 const InputEvent* event = consume();
912 ASSERT_NE(nullptr, event) << mName.c_str()
913 << ": consumer should have returned non-NULL event.";
914 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
915 << "Got " << inputEventTypeToString(event->getType())
916 << " event instead of TOUCH_MODE event";
917
918 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
919 << mName.c_str() << ": event displayId should always be NONE.";
920 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
921 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
922 }
923
chaviwd1c23182019-12-20 18:44:56 -0800924 void assertNoEvents() {
925 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700926 if (event == nullptr) {
927 return;
928 }
929 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
930 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
931 ADD_FAILURE() << "Received key event "
932 << KeyEvent::actionToString(keyEvent.getAction());
933 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
934 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
935 ADD_FAILURE() << "Received motion event "
936 << MotionEvent::actionToString(motionEvent.getAction());
937 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
938 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
939 ADD_FAILURE() << "Received focus event, hasFocus = "
940 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800941 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
942 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
943 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
944 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000945 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
946 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
947 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
948 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 }
950 FAIL() << mName.c_str()
951 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800952 }
953
954 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
955
956protected:
957 std::unique_ptr<InputConsumer> mConsumer;
958 PreallocatedInputEventFactory mEventFactory;
959
960 std::string mName;
961};
962
chaviw3277faf2021-05-19 16:45:23 -0500963class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800964public:
965 static const int32_t WIDTH = 600;
966 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800967
Chris Yea209fde2020-07-22 13:54:51 -0700968 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700969 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500970 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800971 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500972 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700973 base::Result<std::unique_ptr<InputChannel>> channel =
974 dispatcher->createInputChannel(name);
975 token = (*channel)->getConnectionToken();
976 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800977 }
978
979 inputApplicationHandle->updateInfo();
980 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
981
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500982 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700983 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800984 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500985 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500986 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000987 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.frameLeft = 0;
989 mInfo.frameTop = 0;
990 mInfo.frameRight = WIDTH;
991 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700992 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.globalScaleFactor = 1.0;
994 mInfo.touchableRegion.clear();
995 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
996 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700997 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800998 mInfo.hasWallpaper = false;
999 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001000 mInfo.ownerPid = INJECTOR_PID;
1001 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.displayId = displayId;
1003 }
1004
Arthur Hungabbb9d82021-09-01 14:52:30 +00001005 sp<FakeWindowHandle> clone(
1006 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001007 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001008 sp<FakeWindowHandle> handle =
1009 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1010 displayId, mInfo.token);
1011 return handle;
1012 }
1013
Vishnu Nair47074b82020-08-14 11:54:47 -07001014 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001015
Vishnu Nair958da932020-08-21 17:12:37 -07001016 void setVisible(bool visible) { mInfo.visible = visible; }
1017
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001018 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001019 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001020 }
1021
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001022 void setPaused(bool paused) { mInfo.paused = paused; }
1023
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001024 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1025
chaviw3277faf2021-05-19 16:45:23 -05001026 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001027
Bernardo Rufino7393d172021-02-26 13:56:11 +00001028 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1029
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001030 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001031 mInfo.frameLeft = frame.left;
1032 mInfo.frameTop = frame.top;
1033 mInfo.frameRight = frame.right;
1034 mInfo.frameBottom = frame.bottom;
1035 mInfo.touchableRegion.clear();
1036 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001037
1038 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1039 ui::Transform translate;
1040 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1041 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001042 }
1043
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001044 void setType(WindowInfo::Type type) { mInfo.type = type; }
1045
1046 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1047
chaviw3277faf2021-05-19 16:45:23 -05001048 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001049
chaviw3277faf2021-05-19 16:45:23 -05001050 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001051
chaviw3277faf2021-05-19 16:45:23 -05001052 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001053
chaviw9eaa22c2020-07-01 16:21:27 -07001054 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1055 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1056 }
1057
1058 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001059
yunho.shinf4a80b82020-11-16 21:13:57 +09001060 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1061
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001062 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1063 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1064 expectedFlags);
1065 }
1066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1068 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1069 }
1070
Svet Ganov5d3bc372020-01-26 23:11:07 -08001071 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001072 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001073 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1074 expectedFlags);
1075 }
1076
1077 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001078 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001079 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1080 expectedFlags);
1081 }
1082
1083 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001084 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001085 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1086 }
1087
1088 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1089 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001090 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1091 expectedFlags);
1092 }
1093
Svet Ganov5d3bc372020-01-26 23:11:07 -08001094 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001095 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1096 int32_t expectedFlags = 0) {
1097 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1098 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001099 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1100 }
1101
1102 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001103 int32_t expectedFlags = 0) {
1104 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1105 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001106 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1107 }
1108
1109 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001110 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001111 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1112 expectedFlags);
1113 }
1114
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001115 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1116 int32_t expectedFlags = 0) {
1117 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1118 expectedFlags);
1119 }
1120
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001121 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1122 ASSERT_NE(mInputReceiver, nullptr)
1123 << "Cannot consume events from a window with no receiver";
1124 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1125 }
1126
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 void consumeCaptureEvent(bool hasCapture) {
1128 ASSERT_NE(mInputReceiver, nullptr)
1129 << "Cannot consume events from a window with no receiver";
1130 mInputReceiver->consumeCaptureEvent(hasCapture);
1131 }
1132
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001133 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1134 std::optional<int32_t> expectedDisplayId,
1135 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001136 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1137 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1138 expectedFlags);
1139 }
1140
arthurhungb89ccb02020-12-30 16:19:01 +08001141 void consumeDragEvent(bool isExiting, float x, float y) {
1142 mInputReceiver->consumeDragEvent(isExiting, x, y);
1143 }
1144
Antonio Kantekf16f2832021-09-28 04:39:20 +00001145 void consumeTouchModeEvent(bool inTouchMode) {
1146 ASSERT_NE(mInputReceiver, nullptr)
1147 << "Cannot consume events from a window with no receiver";
1148 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1149 }
1150
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001151 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001152 if (mInputReceiver == nullptr) {
1153 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1154 return std::nullopt;
1155 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001156 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001157 }
1158
1159 void finishEvent(uint32_t sequenceNum) {
1160 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1161 mInputReceiver->finishEvent(sequenceNum);
1162 }
1163
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001164 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1165 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1166 mInputReceiver->sendTimeline(inputEventId, timeline);
1167 }
1168
chaviwaf87b3e2019-10-01 16:59:28 -07001169 InputEvent* consume() {
1170 if (mInputReceiver == nullptr) {
1171 return nullptr;
1172 }
1173 return mInputReceiver->consume();
1174 }
1175
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001176 MotionEvent* consumeMotion() {
1177 InputEvent* event = consume();
1178 if (event == nullptr) {
1179 ADD_FAILURE() << "Consume failed : no event";
1180 return nullptr;
1181 }
1182 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1183 ADD_FAILURE() << "Instead of motion event, got "
1184 << inputEventTypeToString(event->getType());
1185 return nullptr;
1186 }
1187 return static_cast<MotionEvent*>(event);
1188 }
1189
Arthur Hungb92218b2018-08-14 12:00:21 +08001190 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001191 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001192 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001193 return; // Can't receive events if the window does not have input channel
1194 }
1195 ASSERT_NE(nullptr, mInputReceiver)
1196 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001197 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001198 }
1199
chaviwaf87b3e2019-10-01 16:59:28 -07001200 sp<IBinder> getToken() { return mInfo.token; }
1201
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001202 const std::string& getName() { return mName; }
1203
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001204 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1205 mInfo.ownerPid = ownerPid;
1206 mInfo.ownerUid = ownerUid;
1207 }
1208
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001209 void destroyReceiver() { mInputReceiver = nullptr; }
1210
chaviwd1c23182019-12-20 18:44:56 -08001211private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001212 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001213 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001214 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001215};
1216
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001217std::atomic<int32_t> FakeWindowHandle::sId{1};
1218
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001219static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001220 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001221 int32_t displayId = ADISPLAY_ID_NONE,
1222 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001223 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1224 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001225 KeyEvent event;
1226 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1227
1228 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001229 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001230 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1231 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001232
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001233 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1234 if (!allowKeyRepeat) {
1235 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1236 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001237 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001238 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001239 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001240}
1241
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001242static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001243 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001244 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1245}
1246
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001247// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1248// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1249// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001250static InputEventInjectionResult injectKeyDownNoRepeat(
1251 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001252 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1253 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1254 /* allowKeyRepeat */ false);
1255}
1256
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001257static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001258 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001259 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1260}
1261
Garfield Tandf26e862020-07-01 20:18:19 -07001262class PointerBuilder {
1263public:
1264 PointerBuilder(int32_t id, int32_t toolType) {
1265 mProperties.clear();
1266 mProperties.id = id;
1267 mProperties.toolType = toolType;
1268 mCoords.clear();
1269 }
1270
1271 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1272
1273 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1274
1275 PointerBuilder& axis(int32_t axis, float value) {
1276 mCoords.setAxisValue(axis, value);
1277 return *this;
1278 }
1279
1280 PointerProperties buildProperties() const { return mProperties; }
1281
1282 PointerCoords buildCoords() const { return mCoords; }
1283
1284private:
1285 PointerProperties mProperties;
1286 PointerCoords mCoords;
1287};
1288
1289class MotionEventBuilder {
1290public:
1291 MotionEventBuilder(int32_t action, int32_t source) {
1292 mAction = action;
1293 mSource = source;
1294 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1295 }
1296
1297 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1298 mEventTime = eventTime;
1299 return *this;
1300 }
1301
1302 MotionEventBuilder& displayId(int32_t displayId) {
1303 mDisplayId = displayId;
1304 return *this;
1305 }
1306
1307 MotionEventBuilder& actionButton(int32_t actionButton) {
1308 mActionButton = actionButton;
1309 return *this;
1310 }
1311
arthurhung6d4bed92021-03-17 11:59:33 +08001312 MotionEventBuilder& buttonState(int32_t buttonState) {
1313 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001314 return *this;
1315 }
1316
1317 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1318 mRawXCursorPosition = rawXCursorPosition;
1319 return *this;
1320 }
1321
1322 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1323 mRawYCursorPosition = rawYCursorPosition;
1324 return *this;
1325 }
1326
1327 MotionEventBuilder& pointer(PointerBuilder pointer) {
1328 mPointers.push_back(pointer);
1329 return *this;
1330 }
1331
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001332 MotionEventBuilder& addFlag(uint32_t flags) {
1333 mFlags |= flags;
1334 return *this;
1335 }
1336
Garfield Tandf26e862020-07-01 20:18:19 -07001337 MotionEvent build() {
1338 std::vector<PointerProperties> pointerProperties;
1339 std::vector<PointerCoords> pointerCoords;
1340 for (const PointerBuilder& pointer : mPointers) {
1341 pointerProperties.push_back(pointer.buildProperties());
1342 pointerCoords.push_back(pointer.buildCoords());
1343 }
1344
1345 // Set mouse cursor position for the most common cases to avoid boilerplate.
1346 if (mSource == AINPUT_SOURCE_MOUSE &&
1347 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1348 mPointers.size() == 1) {
1349 mRawXCursorPosition = pointerCoords[0].getX();
1350 mRawYCursorPosition = pointerCoords[0].getY();
1351 }
1352
1353 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001354 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001355 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001356 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001357 mButtonState, MotionClassification::NONE, identityTransform,
1358 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001359 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1360 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001361
1362 return event;
1363 }
1364
1365private:
1366 int32_t mAction;
1367 int32_t mSource;
1368 nsecs_t mEventTime;
1369 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1370 int32_t mActionButton{0};
1371 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001372 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001373 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1374 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1375
1376 std::vector<PointerBuilder> mPointers;
1377};
1378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001379static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001380 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001381 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001382 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001383 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1384 injectionTimeout,
1385 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1386}
1387
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001388static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001389 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1390 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001391 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001392 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1393 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001394 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001395 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001396 MotionEvent event = MotionEventBuilder(action, source)
1397 .displayId(displayId)
1398 .eventTime(eventTime)
1399 .rawXCursorPosition(cursorPosition.x)
1400 .rawYCursorPosition(cursorPosition.y)
1401 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1402 .x(position.x)
1403 .y(position.y))
1404 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001405
1406 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001407 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001408}
1409
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001410static InputEventInjectionResult injectMotionDown(
1411 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1412 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001413 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001414}
1415
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001416static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001417 int32_t source, int32_t displayId,
1418 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001419 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001420}
1421
Jackal Guof9696682018-10-05 12:23:23 +08001422static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1423 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1424 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001425 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1426 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1427 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001428
1429 return args;
1430}
1431
chaviwd1c23182019-12-20 18:44:56 -08001432static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1433 const std::vector<PointF>& points) {
1434 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001435 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1436 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1437 }
1438
chaviwd1c23182019-12-20 18:44:56 -08001439 PointerProperties pointerProperties[pointerCount];
1440 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001441
chaviwd1c23182019-12-20 18:44:56 -08001442 for (size_t i = 0; i < pointerCount; i++) {
1443 pointerProperties[i].clear();
1444 pointerProperties[i].id = i;
1445 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001446
chaviwd1c23182019-12-20 18:44:56 -08001447 pointerCoords[i].clear();
1448 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1449 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1450 }
Jackal Guof9696682018-10-05 12:23:23 +08001451
1452 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1453 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001454 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001455 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1456 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001457 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1458 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001459 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1460 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001461
1462 return args;
1463}
1464
chaviwd1c23182019-12-20 18:44:56 -08001465static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1466 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1467}
1468
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001469static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1470 const PointerCaptureRequest& request) {
1471 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001472}
1473
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001474/**
1475 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1476 * broken channel.
1477 */
1478TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1479 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1480 sp<FakeWindowHandle> window =
1481 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1482 ADISPLAY_ID_DEFAULT);
1483
1484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1485
1486 // Window closes its channel, but the window remains.
1487 window->destroyReceiver();
1488 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1489}
1490
Arthur Hungb92218b2018-08-14 12:00:21 +08001491TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001492 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001493 sp<FakeWindowHandle> window =
1494 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001495
Arthur Hung72d8dc32020-03-28 00:48:39 +00001496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001500
1501 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001502 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001503}
1504
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001505TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1506 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1507 sp<FakeWindowHandle> window =
1508 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1509
1510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1511 // Inject a MotionEvent to an unknown display.
1512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1513 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1515
1516 // Window should receive motion event.
1517 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1518}
1519
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001520/**
1521 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1522 * To ensure that window receives only events that were directly inside of it, add
1523 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1524 * when finding touched windows.
1525 * This test serves as a sanity check for the next test, where setInputWindows is
1526 * called twice.
1527 */
1528TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001529 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001530 sp<FakeWindowHandle> window =
1531 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1532 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001533 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001534
1535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1538 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001540
1541 // Window should receive motion event.
1542 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1543}
1544
1545/**
1546 * Calling setInputWindows twice, with the same info, should not cause any issues.
1547 * To ensure that window receives only events that were directly inside of it, add
1548 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1549 * when finding touched windows.
1550 */
1551TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001552 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001553 sp<FakeWindowHandle> window =
1554 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1555 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001556 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001557
1558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1562 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001564
1565 // Window should receive motion event.
1566 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1567}
1568
Arthur Hungb92218b2018-08-14 12:00:21 +08001569// The foreground window should receive the first touch down event.
1570TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001572 sp<FakeWindowHandle> windowTop =
1573 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1574 sp<FakeWindowHandle> windowSecond =
1575 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001576
Arthur Hung72d8dc32020-03-28 00:48:39 +00001577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1579 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001581
1582 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001583 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001584 windowSecond->assertNoEvents();
1585}
1586
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001587/**
1588 * Two windows: A top window, and a wallpaper behind the window.
1589 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1590 * gets ACTION_CANCEL.
1591 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1592 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1593 */
1594TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1596 sp<FakeWindowHandle> foregroundWindow =
1597 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1598 foregroundWindow->setHasWallpaper(true);
1599 sp<FakeWindowHandle> wallpaperWindow =
1600 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1601 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1602 constexpr int expectedWallpaperFlags =
1603 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1604
1605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1608 {100, 200}))
1609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1610
1611 // Both foreground window and its wallpaper should receive the touch down
1612 foregroundWindow->consumeMotionDown();
1613 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1614
1615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1616 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1617 ADISPLAY_ID_DEFAULT, {110, 200}))
1618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1619
1620 foregroundWindow->consumeMotionMove();
1621 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1622
1623 // Now the foreground window goes away, but the wallpaper stays
1624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1625 foregroundWindow->consumeMotionCancel();
1626 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1627 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1628}
1629
1630/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001631 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1632 * with the following differences:
1633 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1634 * clean up the connection.
1635 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1636 * Ensure that there's no crash in the dispatcher.
1637 */
1638TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1640 sp<FakeWindowHandle> foregroundWindow =
1641 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1642 foregroundWindow->setHasWallpaper(true);
1643 sp<FakeWindowHandle> wallpaperWindow =
1644 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1645 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1646 constexpr int expectedWallpaperFlags =
1647 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1648
1649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1652 {100, 200}))
1653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1654
1655 // Both foreground window and its wallpaper should receive the touch down
1656 foregroundWindow->consumeMotionDown();
1657 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1658
1659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1660 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1661 ADISPLAY_ID_DEFAULT, {110, 200}))
1662 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1663
1664 foregroundWindow->consumeMotionMove();
1665 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1666
1667 // Wallpaper closes its channel, but the window remains.
1668 wallpaperWindow->destroyReceiver();
1669 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1670
1671 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1672 // is no longer valid.
1673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1674 foregroundWindow->consumeMotionCancel();
1675}
1676
1677/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001678 * A single window that receives touch (on top), and a wallpaper window underneath it.
1679 * The top window gets a multitouch gesture.
1680 * Ensure that wallpaper gets the same gesture.
1681 */
1682TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1683 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1684 sp<FakeWindowHandle> window =
1685 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1686 window->setHasWallpaper(true);
1687
1688 sp<FakeWindowHandle> wallpaperWindow =
1689 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1690 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1691 constexpr int expectedWallpaperFlags =
1692 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1693
1694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1695
1696 // Touch down on top window
1697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1699 {100, 100}))
1700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1701
1702 // Both top window and its wallpaper should receive the touch down
1703 window->consumeMotionDown();
1704 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1705
1706 // Second finger down on the top window
1707 const MotionEvent secondFingerDownEvent =
1708 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1709 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1710 AINPUT_SOURCE_TOUCHSCREEN)
1711 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1712 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1713 .x(100)
1714 .y(100))
1715 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1716 .x(150)
1717 .y(150))
1718 .build();
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1721 InputEventInjectionSync::WAIT_FOR_RESULT))
1722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1723
1724 window->consumeMotionPointerDown(1 /* pointerIndex */);
1725 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1726 expectedWallpaperFlags);
1727 window->assertNoEvents();
1728 wallpaperWindow->assertNoEvents();
1729}
1730
1731/**
1732 * Two windows: a window on the left and window on the right.
1733 * A third window, wallpaper, is behind both windows, and spans both top windows.
1734 * The first touch down goes to the left window. A second pointer touches down on the right window.
1735 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1736 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1737 * ACTION_POINTER_DOWN(1).
1738 */
1739TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1740 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1741 sp<FakeWindowHandle> leftWindow =
1742 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1743 leftWindow->setFrame(Rect(0, 0, 200, 200));
1744 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1745 leftWindow->setHasWallpaper(true);
1746
1747 sp<FakeWindowHandle> rightWindow =
1748 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1749 rightWindow->setFrame(Rect(200, 0, 400, 200));
1750 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1751 rightWindow->setHasWallpaper(true);
1752
1753 sp<FakeWindowHandle> wallpaperWindow =
1754 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1755 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1756 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1757 constexpr int expectedWallpaperFlags =
1758 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1759
1760 mDispatcher->setInputWindows(
1761 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1762
1763 // Touch down on left window
1764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1766 {100, 100}))
1767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1768
1769 // Both foreground window and its wallpaper should receive the touch down
1770 leftWindow->consumeMotionDown();
1771 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1772
1773 // Second finger down on the right window
1774 const MotionEvent secondFingerDownEvent =
1775 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1776 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1777 AINPUT_SOURCE_TOUCHSCREEN)
1778 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1779 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1780 .x(100)
1781 .y(100))
1782 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1783 .x(300)
1784 .y(100))
1785 .build();
1786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1787 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1788 InputEventInjectionSync::WAIT_FOR_RESULT))
1789 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1790
1791 leftWindow->consumeMotionMove();
1792 // Since the touch is split, right window gets ACTION_DOWN
1793 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1794 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1795 expectedWallpaperFlags);
1796
1797 // Now, leftWindow, which received the first finger, disappears.
1798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1799 leftWindow->consumeMotionCancel();
1800 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1801 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1802
1803 // The pointer that's still down on the right window moves, and goes to the right window only.
1804 // As far as the dispatcher's concerned though, both pointers are still present.
1805 const MotionEvent secondFingerMoveEvent =
1806 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1807 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1808 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1809 .x(100)
1810 .y(100))
1811 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1812 .x(310)
1813 .y(110))
1814 .build();
1815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1816 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1817 InputEventInjectionSync::WAIT_FOR_RESULT));
1818 rightWindow->consumeMotionMove();
1819
1820 leftWindow->assertNoEvents();
1821 rightWindow->assertNoEvents();
1822 wallpaperWindow->assertNoEvents();
1823}
1824
Garfield Tandf26e862020-07-01 20:18:19 -07001825TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001826 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001827 sp<FakeWindowHandle> windowLeft =
1828 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1829 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001830 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001831 sp<FakeWindowHandle> windowRight =
1832 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1833 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001834 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001835
1836 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1837
1838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1839
1840 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001841 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001842 injectMotionEvent(mDispatcher,
1843 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1844 AINPUT_SOURCE_MOUSE)
1845 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1846 .x(900)
1847 .y(400))
1848 .build()));
1849 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1850 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1851 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1852 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1853
1854 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001856 injectMotionEvent(mDispatcher,
1857 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1858 AINPUT_SOURCE_MOUSE)
1859 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1860 .x(300)
1861 .y(400))
1862 .build()));
1863 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1864 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1865 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1866 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1867 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1868 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1869
1870 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001872 injectMotionEvent(mDispatcher,
1873 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1874 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1876 .x(300)
1877 .y(400))
1878 .build()));
1879 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1880
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001882 injectMotionEvent(mDispatcher,
1883 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1884 AINPUT_SOURCE_MOUSE)
1885 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1886 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1887 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1888 .x(300)
1889 .y(400))
1890 .build()));
1891 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1892 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001895 injectMotionEvent(mDispatcher,
1896 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1897 AINPUT_SOURCE_MOUSE)
1898 .buttonState(0)
1899 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1900 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1901 .x(300)
1902 .y(400))
1903 .build()));
1904 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1905 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1906
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001908 injectMotionEvent(mDispatcher,
1909 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1910 .buttonState(0)
1911 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1912 .x(300)
1913 .y(400))
1914 .build()));
1915 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1916
1917 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001919 injectMotionEvent(mDispatcher,
1920 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1921 AINPUT_SOURCE_MOUSE)
1922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1923 .x(900)
1924 .y(400))
1925 .build()));
1926 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1927 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1928 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1929 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1930 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1931 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1932}
1933
1934// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1935// directly in this test.
1936TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001938 sp<FakeWindowHandle> window =
1939 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1940 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001941 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001942
1943 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1944
1945 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1946
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001948 injectMotionEvent(mDispatcher,
1949 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1950 AINPUT_SOURCE_MOUSE)
1951 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1952 .x(300)
1953 .y(400))
1954 .build()));
1955 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1956 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1957
1958 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001960 injectMotionEvent(mDispatcher,
1961 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1962 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1963 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1964 .x(300)
1965 .y(400))
1966 .build()));
1967 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1972 AINPUT_SOURCE_MOUSE)
1973 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1974 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1975 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1976 .x(300)
1977 .y(400))
1978 .build()));
1979 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1980 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1981
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001983 injectMotionEvent(mDispatcher,
1984 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1985 AINPUT_SOURCE_MOUSE)
1986 .buttonState(0)
1987 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1988 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1989 .x(300)
1990 .y(400))
1991 .build()));
1992 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1993 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1994
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001996 injectMotionEvent(mDispatcher,
1997 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1998 .buttonState(0)
1999 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2000 .x(300)
2001 .y(400))
2002 .build()));
2003 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002006 injectMotionEvent(mDispatcher,
2007 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2008 AINPUT_SOURCE_MOUSE)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2014 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2015}
2016
Garfield Tan00f511d2019-06-12 16:55:40 -07002017TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002019
2020 sp<FakeWindowHandle> windowLeft =
2021 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2022 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002023 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002024 sp<FakeWindowHandle> windowRight =
2025 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2026 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002027 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002028
2029 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2030
Arthur Hung72d8dc32020-03-28 00:48:39 +00002031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002032
2033 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2034 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002036 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002037 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002038 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002039 windowRight->assertNoEvents();
2040}
2041
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002042TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002044 sp<FakeWindowHandle> window =
2045 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002046 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002047
Arthur Hung72d8dc32020-03-28 00:48:39 +00002048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002049 setFocusedWindow(window);
2050
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002051 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002052
2053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2054 mDispatcher->notifyKey(&keyArgs);
2055
2056 // Window should receive key down event.
2057 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2058
2059 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2060 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002061 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002062 mDispatcher->notifyDeviceReset(&args);
2063 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2064 AKEY_EVENT_FLAG_CANCELED);
2065}
2066
2067TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002068 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002069 sp<FakeWindowHandle> window =
2070 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2071
Arthur Hung72d8dc32020-03-28 00:48:39 +00002072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002073
2074 NotifyMotionArgs motionArgs =
2075 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2076 ADISPLAY_ID_DEFAULT);
2077 mDispatcher->notifyMotion(&motionArgs);
2078
2079 // Window should receive motion down event.
2080 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2081
2082 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2083 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002084 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002085 mDispatcher->notifyDeviceReset(&args);
2086 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2087 0 /*expectedFlags*/);
2088}
2089
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002090/**
2091 * Ensure the correct coordinate spaces are used by InputDispatcher.
2092 *
2093 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2094 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2095 * space.
2096 */
2097class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2098public:
2099 void SetUp() override {
2100 InputDispatcherTest::SetUp();
2101 mDisplayInfos.clear();
2102 mWindowInfos.clear();
2103 }
2104
2105 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2106 gui::DisplayInfo info;
2107 info.displayId = displayId;
2108 info.transform = transform;
2109 mDisplayInfos.push_back(std::move(info));
2110 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2111 }
2112
2113 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2114 mWindowInfos.push_back(*windowHandle->getInfo());
2115 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2116 }
2117
2118 // Set up a test scenario where the display has a scaled projection and there are two windows
2119 // on the display.
2120 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2121 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2122 // respectively.
2123 ui::Transform displayTransform;
2124 displayTransform.set(2, 0, 0, 4);
2125 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2126
2127 std::shared_ptr<FakeApplicationHandle> application =
2128 std::make_shared<FakeApplicationHandle>();
2129
2130 // Add two windows to the display. Their frames are represented in the display space.
2131 sp<FakeWindowHandle> firstWindow =
2132 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2133 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2134 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2135 addWindow(firstWindow);
2136
2137 sp<FakeWindowHandle> secondWindow =
2138 new FakeWindowHandle(application, mDispatcher, "Second Window",
2139 ADISPLAY_ID_DEFAULT);
2140 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2141 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2142 addWindow(secondWindow);
2143 return {std::move(firstWindow), std::move(secondWindow)};
2144 }
2145
2146private:
2147 std::vector<gui::DisplayInfo> mDisplayInfos;
2148 std::vector<gui::WindowInfo> mWindowInfos;
2149};
2150
2151TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2152 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2153 // Send down to the first window. The point is represented in the display space. The point is
2154 // selected so that if the hit test was done with the transform applied to it, then it would
2155 // end up in the incorrect window.
2156 NotifyMotionArgs downMotionArgs =
2157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2158 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2159 mDispatcher->notifyMotion(&downMotionArgs);
2160
2161 firstWindow->consumeMotionDown();
2162 secondWindow->assertNoEvents();
2163}
2164
2165// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2166// the event should be treated as being in the logical display space.
2167TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2168 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2169 // Send down to the first window. The point is represented in the logical display space. The
2170 // point is selected so that if the hit test was done in logical display space, then it would
2171 // end up in the incorrect window.
2172 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2173 PointF{75 * 2, 55 * 4});
2174
2175 firstWindow->consumeMotionDown();
2176 secondWindow->assertNoEvents();
2177}
2178
2179TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2180 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2181
2182 // Send down to the second window.
2183 NotifyMotionArgs downMotionArgs =
2184 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2185 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2186 mDispatcher->notifyMotion(&downMotionArgs);
2187
2188 firstWindow->assertNoEvents();
2189 const MotionEvent* event = secondWindow->consumeMotion();
2190 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2191
2192 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2193 EXPECT_EQ(300, event->getRawX(0));
2194 EXPECT_EQ(880, event->getRawY(0));
2195
2196 // Ensure that the x and y values are in the window's coordinate space.
2197 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2198 // the logical display space. This will be the origin of the window space.
2199 EXPECT_EQ(100, event->getX(0));
2200 EXPECT_EQ(80, event->getY(0));
2201}
2202
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002203using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2204 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002205
2206class TransferTouchFixture : public InputDispatcherTest,
2207 public ::testing::WithParamInterface<TransferFunction> {};
2208
2209TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002210 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002211
2212 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002213 sp<FakeWindowHandle> firstWindow =
2214 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2215 sp<FakeWindowHandle> secondWindow =
2216 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002217
2218 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002220
2221 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002222 NotifyMotionArgs downMotionArgs =
2223 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2224 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002225 mDispatcher->notifyMotion(&downMotionArgs);
2226 // Only the first window should get the down event
2227 firstWindow->consumeMotionDown();
2228 secondWindow->assertNoEvents();
2229
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002230 // Transfer touch to the second window
2231 TransferFunction f = GetParam();
2232 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2233 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002234 // The first window gets cancel and the second gets down
2235 firstWindow->consumeMotionCancel();
2236 secondWindow->consumeMotionDown();
2237
2238 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002239 NotifyMotionArgs upMotionArgs =
2240 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2241 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002242 mDispatcher->notifyMotion(&upMotionArgs);
2243 // The first window gets no events and the second gets up
2244 firstWindow->assertNoEvents();
2245 secondWindow->consumeMotionUp();
2246}
2247
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002248TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002249 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002250
2251 PointF touchPoint = {10, 10};
2252
2253 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002254 sp<FakeWindowHandle> firstWindow =
2255 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2256 sp<FakeWindowHandle> secondWindow =
2257 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002258
2259 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002261
2262 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002263 NotifyMotionArgs downMotionArgs =
2264 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2265 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266 mDispatcher->notifyMotion(&downMotionArgs);
2267 // Only the first window should get the down event
2268 firstWindow->consumeMotionDown();
2269 secondWindow->assertNoEvents();
2270
2271 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002272 NotifyMotionArgs pointerDownMotionArgs =
2273 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2274 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2275 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2276 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002277 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2278 // Only the first window should get the pointer down event
2279 firstWindow->consumeMotionPointerDown(1);
2280 secondWindow->assertNoEvents();
2281
2282 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002283 TransferFunction f = GetParam();
2284 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2285 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002286 // The first window gets cancel and the second gets down and pointer down
2287 firstWindow->consumeMotionCancel();
2288 secondWindow->consumeMotionDown();
2289 secondWindow->consumeMotionPointerDown(1);
2290
2291 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002292 NotifyMotionArgs pointerUpMotionArgs =
2293 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2294 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2295 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2296 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002297 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2298 // The first window gets nothing and the second gets pointer up
2299 firstWindow->assertNoEvents();
2300 secondWindow->consumeMotionPointerUp(1);
2301
2302 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002303 NotifyMotionArgs upMotionArgs =
2304 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2305 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002306 mDispatcher->notifyMotion(&upMotionArgs);
2307 // The first window gets nothing and the second gets up
2308 firstWindow->assertNoEvents();
2309 secondWindow->consumeMotionUp();
2310}
2311
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002312// For the cases of single pointer touch and two pointers non-split touch, the api's
2313// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2314// for the case where there are multiple pointers split across several windows.
2315INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2316 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002317 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2318 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002319 return dispatcher->transferTouch(destChannelToken);
2320 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002321 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2322 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002323 return dispatcher->transferTouchFocus(from, to,
2324 false /*isDragAndDrop*/);
2325 }));
2326
Svet Ganov5d3bc372020-01-26 23:11:07 -08002327TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002329
2330 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002331 sp<FakeWindowHandle> firstWindow =
2332 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002333 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002334 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002335
2336 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002337 sp<FakeWindowHandle> secondWindow =
2338 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002339 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002340 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002341
2342 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344
2345 PointF pointInFirst = {300, 200};
2346 PointF pointInSecond = {300, 600};
2347
2348 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002349 NotifyMotionArgs firstDownMotionArgs =
2350 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2351 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002352 mDispatcher->notifyMotion(&firstDownMotionArgs);
2353 // Only the first window should get the down event
2354 firstWindow->consumeMotionDown();
2355 secondWindow->assertNoEvents();
2356
2357 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002358 NotifyMotionArgs secondDownMotionArgs =
2359 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2360 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2361 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2362 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002363 mDispatcher->notifyMotion(&secondDownMotionArgs);
2364 // The first window gets a move and the second a down
2365 firstWindow->consumeMotionMove();
2366 secondWindow->consumeMotionDown();
2367
2368 // Transfer touch focus to the second window
2369 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2370 // The first window gets cancel and the new gets pointer down (it already saw down)
2371 firstWindow->consumeMotionCancel();
2372 secondWindow->consumeMotionPointerDown(1);
2373
2374 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002375 NotifyMotionArgs pointerUpMotionArgs =
2376 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2377 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2378 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2379 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002380 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2381 // The first window gets nothing and the second gets pointer up
2382 firstWindow->assertNoEvents();
2383 secondWindow->consumeMotionPointerUp(1);
2384
2385 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002386 NotifyMotionArgs upMotionArgs =
2387 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2388 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389 mDispatcher->notifyMotion(&upMotionArgs);
2390 // The first window gets nothing and the second gets up
2391 firstWindow->assertNoEvents();
2392 secondWindow->consumeMotionUp();
2393}
2394
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002395// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2396// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2397// touch is not supported, so the touch should continue on those windows and the transferred-to
2398// window should get nothing.
2399TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2400 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2401
2402 // Create a non touch modal window that supports split touch
2403 sp<FakeWindowHandle> firstWindow =
2404 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2405 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002406 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002407
2408 // Create a non touch modal window that supports split touch
2409 sp<FakeWindowHandle> secondWindow =
2410 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2411 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002412 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002413
2414 // Add the windows to the dispatcher
2415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2416
2417 PointF pointInFirst = {300, 200};
2418 PointF pointInSecond = {300, 600};
2419
2420 // Send down to the first window
2421 NotifyMotionArgs firstDownMotionArgs =
2422 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2423 ADISPLAY_ID_DEFAULT, {pointInFirst});
2424 mDispatcher->notifyMotion(&firstDownMotionArgs);
2425 // Only the first window should get the down event
2426 firstWindow->consumeMotionDown();
2427 secondWindow->assertNoEvents();
2428
2429 // Send down to the second window
2430 NotifyMotionArgs secondDownMotionArgs =
2431 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2432 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2433 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2434 {pointInFirst, pointInSecond});
2435 mDispatcher->notifyMotion(&secondDownMotionArgs);
2436 // The first window gets a move and the second a down
2437 firstWindow->consumeMotionMove();
2438 secondWindow->consumeMotionDown();
2439
2440 // Transfer touch focus to the second window
2441 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2442 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2443 ASSERT_FALSE(transferred);
2444 firstWindow->assertNoEvents();
2445 secondWindow->assertNoEvents();
2446
2447 // The rest of the dispatch should proceed as normal
2448 // Send pointer up to the second window
2449 NotifyMotionArgs pointerUpMotionArgs =
2450 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2451 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2452 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2453 {pointInFirst, pointInSecond});
2454 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2455 // The first window gets MOVE and the second gets pointer up
2456 firstWindow->consumeMotionMove();
2457 secondWindow->consumeMotionUp();
2458
2459 // Send up event to the first window
2460 NotifyMotionArgs upMotionArgs =
2461 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2462 ADISPLAY_ID_DEFAULT);
2463 mDispatcher->notifyMotion(&upMotionArgs);
2464 // The first window gets nothing and the second gets up
2465 firstWindow->consumeMotionUp();
2466 secondWindow->assertNoEvents();
2467}
2468
Arthur Hungabbb9d82021-09-01 14:52:30 +00002469// This case will create two windows and one mirrored window on the default display and mirror
2470// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2471// the windows info of second display before default display.
2472TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2473 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2474 sp<FakeWindowHandle> firstWindowInPrimary =
2475 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2476 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2477 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2478 sp<FakeWindowHandle> secondWindowInPrimary =
2479 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2480 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2481 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2482
2483 sp<FakeWindowHandle> mirrorWindowInPrimary =
2484 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2485 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2486 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2487
2488 sp<FakeWindowHandle> firstWindowInSecondary =
2489 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2490 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2491 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2492
2493 sp<FakeWindowHandle> secondWindowInSecondary =
2494 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2495 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2496 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2497
2498 // Update window info, let it find window handle of second display first.
2499 mDispatcher->setInputWindows(
2500 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2501 {ADISPLAY_ID_DEFAULT,
2502 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2503
2504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2505 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2506 {50, 50}))
2507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2508
2509 // Window should receive motion event.
2510 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2511
2512 // Transfer touch focus
2513 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2514 secondWindowInPrimary->getToken()));
2515 // The first window gets cancel.
2516 firstWindowInPrimary->consumeMotionCancel();
2517 secondWindowInPrimary->consumeMotionDown();
2518
2519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2520 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2521 ADISPLAY_ID_DEFAULT, {150, 50}))
2522 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2523 firstWindowInPrimary->assertNoEvents();
2524 secondWindowInPrimary->consumeMotionMove();
2525
2526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2527 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2528 {150, 50}))
2529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2530 firstWindowInPrimary->assertNoEvents();
2531 secondWindowInPrimary->consumeMotionUp();
2532}
2533
2534// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2535// 'transferTouch' api.
2536TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2538 sp<FakeWindowHandle> firstWindowInPrimary =
2539 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2540 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2541 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2542 sp<FakeWindowHandle> secondWindowInPrimary =
2543 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2544 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2545 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2546
2547 sp<FakeWindowHandle> mirrorWindowInPrimary =
2548 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2549 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2550 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2551
2552 sp<FakeWindowHandle> firstWindowInSecondary =
2553 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2554 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2555 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2556
2557 sp<FakeWindowHandle> secondWindowInSecondary =
2558 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2559 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2560 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2561
2562 // Update window info, let it find window handle of second display first.
2563 mDispatcher->setInputWindows(
2564 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2565 {ADISPLAY_ID_DEFAULT,
2566 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2567
2568 // Touch on second display.
2569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2570 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2572
2573 // Window should receive motion event.
2574 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2575
2576 // Transfer touch focus
2577 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2578
2579 // The first window gets cancel.
2580 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2581 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2582
2583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2584 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2585 SECOND_DISPLAY_ID, {150, 50}))
2586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2587 firstWindowInPrimary->assertNoEvents();
2588 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2589
2590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2591 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2593 firstWindowInPrimary->assertNoEvents();
2594 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2595}
2596
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002597TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002598 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002599 sp<FakeWindowHandle> window =
2600 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2601
Vishnu Nair47074b82020-08-14 11:54:47 -07002602 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002604 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002605
2606 window->consumeFocusEvent(true);
2607
2608 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2609 mDispatcher->notifyKey(&keyArgs);
2610
2611 // Window should receive key down event.
2612 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2613}
2614
2615TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002617 sp<FakeWindowHandle> window =
2618 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2619
Arthur Hung72d8dc32020-03-28 00:48:39 +00002620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002621
2622 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2623 mDispatcher->notifyKey(&keyArgs);
2624 mDispatcher->waitForIdle();
2625
2626 window->assertNoEvents();
2627}
2628
2629// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2630TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002631 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002632 sp<FakeWindowHandle> window =
2633 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2634
Arthur Hung72d8dc32020-03-28 00:48:39 +00002635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636
2637 // Send key
2638 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2639 mDispatcher->notifyKey(&keyArgs);
2640 // Send motion
2641 NotifyMotionArgs motionArgs =
2642 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2643 ADISPLAY_ID_DEFAULT);
2644 mDispatcher->notifyMotion(&motionArgs);
2645
2646 // Window should receive only the motion event
2647 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2648 window->assertNoEvents(); // Key event or focus event will not be received
2649}
2650
arthurhungea3f4fc2020-12-21 23:18:53 +08002651TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2652 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2653
2654 // Create first non touch modal window that supports split touch
2655 sp<FakeWindowHandle> firstWindow =
2656 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2657 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002658 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002659
2660 // Create second non touch modal window that supports split touch
2661 sp<FakeWindowHandle> secondWindow =
2662 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2663 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002664 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002665
2666 // Add the windows to the dispatcher
2667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2668
2669 PointF pointInFirst = {300, 200};
2670 PointF pointInSecond = {300, 600};
2671
2672 // Send down to the first window
2673 NotifyMotionArgs firstDownMotionArgs =
2674 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2675 ADISPLAY_ID_DEFAULT, {pointInFirst});
2676 mDispatcher->notifyMotion(&firstDownMotionArgs);
2677 // Only the first window should get the down event
2678 firstWindow->consumeMotionDown();
2679 secondWindow->assertNoEvents();
2680
2681 // Send down to the second window
2682 NotifyMotionArgs secondDownMotionArgs =
2683 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2684 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2685 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2686 {pointInFirst, pointInSecond});
2687 mDispatcher->notifyMotion(&secondDownMotionArgs);
2688 // The first window gets a move and the second a down
2689 firstWindow->consumeMotionMove();
2690 secondWindow->consumeMotionDown();
2691
2692 // Send pointer cancel to the second window
2693 NotifyMotionArgs pointerUpMotionArgs =
2694 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2695 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2696 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2697 {pointInFirst, pointInSecond});
2698 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2699 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2700 // The first window gets move and the second gets cancel.
2701 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2702 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2703
2704 // Send up event.
2705 NotifyMotionArgs upMotionArgs =
2706 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2707 ADISPLAY_ID_DEFAULT);
2708 mDispatcher->notifyMotion(&upMotionArgs);
2709 // The first window gets up and the second gets nothing.
2710 firstWindow->consumeMotionUp();
2711 secondWindow->assertNoEvents();
2712}
2713
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002714TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2715 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2716
2717 sp<FakeWindowHandle> window =
2718 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2720 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2721 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2722 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2723
2724 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2725 window->assertNoEvents();
2726 mDispatcher->waitForIdle();
2727}
2728
chaviwd1c23182019-12-20 18:44:56 -08002729class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002730public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002731 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002732 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002733 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002734 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002735 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002736 }
2737
chaviwd1c23182019-12-20 18:44:56 -08002738 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2739
2740 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2741 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2742 expectedDisplayId, expectedFlags);
2743 }
2744
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002745 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2746
2747 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2748
chaviwd1c23182019-12-20 18:44:56 -08002749 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2750 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2751 expectedDisplayId, expectedFlags);
2752 }
2753
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002754 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2755 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2756 expectedDisplayId, expectedFlags);
2757 }
2758
chaviwd1c23182019-12-20 18:44:56 -08002759 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2760 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2761 expectedDisplayId, expectedFlags);
2762 }
2763
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002764 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2765 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2766 expectedDisplayId, expectedFlags);
2767 }
2768
Arthur Hungfbfa5722021-11-16 02:45:54 +00002769 void consumeMotionPointerDown(int32_t pointerIdx) {
2770 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2771 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2772 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2773 0 /*expectedFlags*/);
2774 }
2775
Evan Rosky84f07f02021-04-16 10:42:42 -07002776 MotionEvent* consumeMotion() {
2777 InputEvent* event = mInputReceiver->consume();
2778 if (!event) {
2779 ADD_FAILURE() << "No event was produced";
2780 return nullptr;
2781 }
2782 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2783 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2784 return nullptr;
2785 }
2786 return static_cast<MotionEvent*>(event);
2787 }
2788
chaviwd1c23182019-12-20 18:44:56 -08002789 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2790
2791private:
2792 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002793};
2794
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002795/**
2796 * Two entities that receive touch: A window, and a global monitor.
2797 * The touch goes to the window, and then the window disappears.
2798 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2799 * for the monitor, as well.
2800 * 1. foregroundWindow
2801 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2802 */
2803TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2804 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2805 sp<FakeWindowHandle> window =
2806 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2807
2808 FakeMonitorReceiver monitor =
2809 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2810 false /*isGestureMonitor*/);
2811
2812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2814 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2815 {100, 200}))
2816 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2817
2818 // Both the foreground window and the global monitor should receive the touch down
2819 window->consumeMotionDown();
2820 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2821
2822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2823 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2824 ADISPLAY_ID_DEFAULT, {110, 200}))
2825 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2826
2827 window->consumeMotionMove();
2828 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2829
2830 // Now the foreground window goes away
2831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2832 window->consumeMotionCancel();
2833 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2834
2835 // If more events come in, there will be no more foreground window to send them to. This will
2836 // cause a cancel for the monitor, as well.
2837 ASSERT_EQ(InputEventInjectionResult::FAILED,
2838 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2839 ADISPLAY_ID_DEFAULT, {120, 200}))
2840 << "Injection should fail because the window was removed";
2841 window->assertNoEvents();
2842 // Global monitor now gets the cancel
2843 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2844}
2845
Michael Wright3a240c42019-12-10 20:53:41 +00002846// Tests for gesture monitors
2847TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002848 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002849 sp<FakeWindowHandle> window =
2850 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002852
chaviwd1c23182019-12-20 18:44:56 -08002853 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2854 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002855
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002857 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002858 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002859 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002860 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002861}
2862
2863TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002864 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002865 sp<FakeWindowHandle> window =
2866 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2867
2868 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002869 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002870
Arthur Hung72d8dc32020-03-28 00:48:39 +00002871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002872 setFocusedWindow(window);
2873
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002874 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002875
chaviwd1c23182019-12-20 18:44:56 -08002876 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2877 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002878
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2880 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002881 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002882 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002883}
2884
2885TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002886 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002887 sp<FakeWindowHandle> window =
2888 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002890
chaviwd1c23182019-12-20 18:44:56 -08002891 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2892 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002898 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002899
2900 window->releaseChannel();
2901
chaviwd1c23182019-12-20 18:44:56 -08002902 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002905 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002907 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002908}
2909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002910TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2911 FakeMonitorReceiver monitor =
2912 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2913 true /*isGestureMonitor*/);
2914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2917 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2918 ASSERT_TRUE(consumeSeq);
2919
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002920 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002921 monitor.finishEvent(*consumeSeq);
2922 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002923 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002924}
2925
Evan Rosky84f07f02021-04-16 10:42:42 -07002926// Tests for gesture monitors
2927TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2928 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2929 sp<FakeWindowHandle> window =
2930 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2931 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2932 window->setWindowOffset(20, 40);
2933 window->setWindowTransform(0, 1, -1, 0);
2934
2935 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2936 true /*isGestureMonitor*/);
2937
2938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2941 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2942 MotionEvent* event = monitor.consumeMotion();
2943 // Even though window has transform, gesture monitor must not.
2944 ASSERT_EQ(ui::Transform(), event->getTransform());
2945}
2946
Arthur Hungb3307ee2021-10-14 10:57:37 +00002947TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2948 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2949 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2950 true /*isGestureMonitor*/);
2951
2952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2955 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2956}
2957
chaviw81e2bb92019-12-18 15:03:51 -08002958TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002959 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002960 sp<FakeWindowHandle> window =
2961 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2962
Arthur Hung72d8dc32020-03-28 00:48:39 +00002963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002964
2965 NotifyMotionArgs motionArgs =
2966 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2967 ADISPLAY_ID_DEFAULT);
2968
2969 mDispatcher->notifyMotion(&motionArgs);
2970 // Window should receive motion down event.
2971 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2972
2973 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002974 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002975 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2976 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2977 motionArgs.pointerCoords[0].getX() - 10);
2978
2979 mDispatcher->notifyMotion(&motionArgs);
2980 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2981 0 /*expectedFlags*/);
2982}
2983
Arthur Hungfbfa5722021-11-16 02:45:54 +00002984TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
2985 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2986 true /*isGestureMonitor*/);
2987
2988 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2989 // Create a non touch modal window that supports split touch
2990 sp<FakeWindowHandle> window =
2991 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2992 window->setFrame(Rect(0, 0, 100, 100));
2993 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
2994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2995
2996 // First finger down, no window touched.
2997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2998 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2999 {100, 200}))
3000 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3001 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3002 window->assertNoEvents();
3003
3004 // Second finger down on window, the window should receive touch down.
3005 const MotionEvent secondFingerDownEvent =
3006 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3007 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3008 AINPUT_SOURCE_TOUCHSCREEN)
3009 .displayId(ADISPLAY_ID_DEFAULT)
3010 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3011 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3012 .x(100)
3013 .y(200))
3014 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3015 .build();
3016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3017 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3018 InputEventInjectionSync::WAIT_FOR_RESULT))
3019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3020
3021 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3022 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3023}
3024
3025TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
3026 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3027 true /*isGestureMonitor*/);
3028
3029 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3030 // Create a non touch modal window that supports split touch
3031 sp<FakeWindowHandle> window =
3032 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3033 window->setFrame(Rect(0, 0, 100, 100));
3034 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3036
3037 // First finger down, no window touched.
3038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3039 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3040 {100, 200}))
3041 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3042 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3043 window->assertNoEvents();
3044
3045 // Gesture monitor pilfer the pointers.
3046 mDispatcher->pilferPointers(monitor.getToken());
3047
3048 // Second finger down on window, the window should not receive touch down.
3049 const MotionEvent secondFingerDownEvent =
3050 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3051 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3052 AINPUT_SOURCE_TOUCHSCREEN)
3053 .displayId(ADISPLAY_ID_DEFAULT)
3054 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3055 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3056 .x(100)
3057 .y(200))
3058 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3059 .build();
3060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3061 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3062 InputEventInjectionSync::WAIT_FOR_RESULT))
3063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3064
3065 window->assertNoEvents();
3066 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3067}
3068
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003069/**
3070 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3071 * the device default right away. In the test scenario, we check both the default value,
3072 * and the action of enabling / disabling.
3073 */
3074TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003075 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003076 sp<FakeWindowHandle> window =
3077 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3078
3079 // Set focused application.
3080 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003081 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003082
3083 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003085 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003086 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3087
3088 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003089 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003091 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3092
3093 SCOPED_TRACE("Disable touch mode");
3094 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003095 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003096 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003098 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003099 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3100
3101 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003102 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003104 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3105
3106 SCOPED_TRACE("Enable touch mode again");
3107 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003108 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003109 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003111 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003112 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3113
3114 window->assertNoEvents();
3115}
3116
Gang Wange9087892020-01-07 12:17:14 -05003117TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003118 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003119 sp<FakeWindowHandle> window =
3120 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3121
3122 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003123 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003124
Arthur Hung72d8dc32020-03-28 00:48:39 +00003125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003126 setFocusedWindow(window);
3127
Gang Wange9087892020-01-07 12:17:14 -05003128 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3129
3130 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3131 mDispatcher->notifyKey(&keyArgs);
3132
3133 InputEvent* event = window->consume();
3134 ASSERT_NE(event, nullptr);
3135
3136 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3137 ASSERT_NE(verified, nullptr);
3138 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3139
3140 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3141 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3142 ASSERT_EQ(keyArgs.source, verified->source);
3143 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3144
3145 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3146
3147 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003148 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003149 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003150 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3151 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3152 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3153 ASSERT_EQ(0, verifiedKey.repeatCount);
3154}
3155
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003156TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003158 sp<FakeWindowHandle> window =
3159 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3160
3161 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3162
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003163 ui::Transform transform;
3164 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3165
3166 gui::DisplayInfo displayInfo;
3167 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3168 displayInfo.transform = transform;
3169
3170 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003171
3172 NotifyMotionArgs motionArgs =
3173 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3174 ADISPLAY_ID_DEFAULT);
3175 mDispatcher->notifyMotion(&motionArgs);
3176
3177 InputEvent* event = window->consume();
3178 ASSERT_NE(event, nullptr);
3179
3180 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3181 ASSERT_NE(verified, nullptr);
3182 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3183
3184 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3185 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3186 EXPECT_EQ(motionArgs.source, verified->source);
3187 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3188
3189 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3190
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003191 const vec2 rawXY =
3192 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3193 motionArgs.pointerCoords[0].getXYValue());
3194 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3195 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003196 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003197 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003198 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003199 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3200 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3201}
3202
chaviw09c8d2d2020-08-24 15:48:26 -07003203/**
3204 * Ensure that separate calls to sign the same data are generating the same key.
3205 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3206 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3207 * tests.
3208 */
3209TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3210 KeyEvent event = getTestKeyEvent();
3211 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3212
3213 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3214 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3215 ASSERT_EQ(hmac1, hmac2);
3216}
3217
3218/**
3219 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3220 */
3221TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3222 KeyEvent event = getTestKeyEvent();
3223 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3224 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3225
3226 verifiedEvent.deviceId += 1;
3227 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3228
3229 verifiedEvent.source += 1;
3230 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3231
3232 verifiedEvent.eventTimeNanos += 1;
3233 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3234
3235 verifiedEvent.displayId += 1;
3236 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3237
3238 verifiedEvent.action += 1;
3239 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3240
3241 verifiedEvent.downTimeNanos += 1;
3242 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3243
3244 verifiedEvent.flags += 1;
3245 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3246
3247 verifiedEvent.keyCode += 1;
3248 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3249
3250 verifiedEvent.scanCode += 1;
3251 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3252
3253 verifiedEvent.metaState += 1;
3254 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3255
3256 verifiedEvent.repeatCount += 1;
3257 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3258}
3259
Vishnu Nair958da932020-08-21 17:12:37 -07003260TEST_F(InputDispatcherTest, SetFocusedWindow) {
3261 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3262 sp<FakeWindowHandle> windowTop =
3263 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3264 sp<FakeWindowHandle> windowSecond =
3265 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3266 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3267
3268 // Top window is also focusable but is not granted focus.
3269 windowTop->setFocusable(true);
3270 windowSecond->setFocusable(true);
3271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3272 setFocusedWindow(windowSecond);
3273
3274 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003275 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3276 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003277
3278 // Focused window should receive event.
3279 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3280 windowTop->assertNoEvents();
3281}
3282
3283TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3284 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3285 sp<FakeWindowHandle> window =
3286 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3287 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3288
3289 window->setFocusable(true);
3290 // Release channel for window is no longer valid.
3291 window->releaseChannel();
3292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3293 setFocusedWindow(window);
3294
3295 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003296 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3297 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003298
3299 // window channel is invalid, so it should not receive any input event.
3300 window->assertNoEvents();
3301}
3302
3303TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3305 sp<FakeWindowHandle> window =
3306 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3307 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3308
3309 // Window is not focusable.
3310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3311 setFocusedWindow(window);
3312
3313 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003314 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3315 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003316
3317 // window is invalid, so it should not receive any input event.
3318 window->assertNoEvents();
3319}
3320
3321TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3322 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3323 sp<FakeWindowHandle> windowTop =
3324 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3325 sp<FakeWindowHandle> windowSecond =
3326 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3327 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3328
3329 windowTop->setFocusable(true);
3330 windowSecond->setFocusable(true);
3331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3332 setFocusedWindow(windowTop);
3333 windowTop->consumeFocusEvent(true);
3334
3335 setFocusedWindow(windowSecond, windowTop);
3336 windowSecond->consumeFocusEvent(true);
3337 windowTop->consumeFocusEvent(false);
3338
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3340 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003341
3342 // Focused window should receive event.
3343 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3344}
3345
3346TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3347 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3348 sp<FakeWindowHandle> windowTop =
3349 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3350 sp<FakeWindowHandle> windowSecond =
3351 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3352 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3353
3354 windowTop->setFocusable(true);
3355 windowSecond->setFocusable(true);
3356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3357 setFocusedWindow(windowSecond, windowTop);
3358
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003359 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3360 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003361
3362 // Event should be dropped.
3363 windowTop->assertNoEvents();
3364 windowSecond->assertNoEvents();
3365}
3366
3367TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3368 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3369 sp<FakeWindowHandle> window =
3370 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3371 sp<FakeWindowHandle> previousFocusedWindow =
3372 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3373 ADISPLAY_ID_DEFAULT);
3374 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3375
3376 window->setFocusable(true);
3377 previousFocusedWindow->setFocusable(true);
3378 window->setVisible(false);
3379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3380 setFocusedWindow(previousFocusedWindow);
3381 previousFocusedWindow->consumeFocusEvent(true);
3382
3383 // Requesting focus on invisible window takes focus from currently focused window.
3384 setFocusedWindow(window);
3385 previousFocusedWindow->consumeFocusEvent(false);
3386
3387 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003389 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003390 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003391
3392 // Window does not get focus event or key down.
3393 window->assertNoEvents();
3394
3395 // Window becomes visible.
3396 window->setVisible(true);
3397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3398
3399 // Window receives focus event.
3400 window->consumeFocusEvent(true);
3401 // Focused window receives key down.
3402 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3403}
3404
Vishnu Nair599f1412021-06-21 10:39:58 -07003405TEST_F(InputDispatcherTest, DisplayRemoved) {
3406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3407 sp<FakeWindowHandle> window =
3408 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3409 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3410
3411 // window is granted focus.
3412 window->setFocusable(true);
3413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3414 setFocusedWindow(window);
3415 window->consumeFocusEvent(true);
3416
3417 // When a display is removed window loses focus.
3418 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3419 window->consumeFocusEvent(false);
3420}
3421
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003422/**
3423 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3424 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3425 * of the 'slipperyEnterWindow'.
3426 *
3427 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3428 * a way so that the touched location is no longer covered by the top window.
3429 *
3430 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3431 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3432 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3433 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3434 * with ACTION_DOWN).
3435 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3436 * window moved itself away from the touched location and had Flag::SLIPPERY.
3437 *
3438 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3439 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3440 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3441 *
3442 * In this test, we ensure that the event received by the bottom window has
3443 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3444 */
3445TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3446 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3447 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3448
3449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3450 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3451
3452 sp<FakeWindowHandle> slipperyExitWindow =
3453 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003454 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003455 // Make sure this one overlaps the bottom window
3456 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3457 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3458 // one. Windows with the same owner are not considered to be occluding each other.
3459 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3460
3461 sp<FakeWindowHandle> slipperyEnterWindow =
3462 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3463 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3464
3465 mDispatcher->setInputWindows(
3466 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3467
3468 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3469 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3470 ADISPLAY_ID_DEFAULT, {{50, 50}});
3471 mDispatcher->notifyMotion(&args);
3472 slipperyExitWindow->consumeMotionDown();
3473 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3474 mDispatcher->setInputWindows(
3475 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3476
3477 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3478 ADISPLAY_ID_DEFAULT, {{51, 51}});
3479 mDispatcher->notifyMotion(&args);
3480
3481 slipperyExitWindow->consumeMotionCancel();
3482
3483 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3484 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3485}
3486
Garfield Tan1c7bc862020-01-28 13:24:04 -08003487class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3488protected:
3489 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3490 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3491
Chris Yea209fde2020-07-22 13:54:51 -07003492 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003493 sp<FakeWindowHandle> mWindow;
3494
3495 virtual void SetUp() override {
3496 mFakePolicy = new FakeInputDispatcherPolicy();
3497 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003498 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003499 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3500 ASSERT_EQ(OK, mDispatcher->start());
3501
3502 setUpWindow();
3503 }
3504
3505 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003506 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003507 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3508
Vishnu Nair47074b82020-08-14 11:54:47 -07003509 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003511 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003512 mWindow->consumeFocusEvent(true);
3513 }
3514
Chris Ye2ad95392020-09-01 13:44:44 -07003515 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003516 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003517 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003518 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3519 mDispatcher->notifyKey(&keyArgs);
3520
3521 // Window should receive key down event.
3522 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3523 }
3524
3525 void expectKeyRepeatOnce(int32_t repeatCount) {
3526 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3527 InputEvent* repeatEvent = mWindow->consume();
3528 ASSERT_NE(nullptr, repeatEvent);
3529
3530 uint32_t eventType = repeatEvent->getType();
3531 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3532
3533 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3534 uint32_t eventAction = repeatKeyEvent->getAction();
3535 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3536 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3537 }
3538
Chris Ye2ad95392020-09-01 13:44:44 -07003539 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003540 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003541 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003542 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3543 mDispatcher->notifyKey(&keyArgs);
3544
3545 // Window should receive key down event.
3546 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3547 0 /*expectedFlags*/);
3548 }
3549};
3550
3551TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003552 sendAndConsumeKeyDown(1 /* deviceId */);
3553 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3554 expectKeyRepeatOnce(repeatCount);
3555 }
3556}
3557
3558TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3559 sendAndConsumeKeyDown(1 /* deviceId */);
3560 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3561 expectKeyRepeatOnce(repeatCount);
3562 }
3563 sendAndConsumeKeyDown(2 /* deviceId */);
3564 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003565 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3566 expectKeyRepeatOnce(repeatCount);
3567 }
3568}
3569
3570TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003571 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003572 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003573 sendAndConsumeKeyUp(1 /* deviceId */);
3574 mWindow->assertNoEvents();
3575}
3576
3577TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3578 sendAndConsumeKeyDown(1 /* deviceId */);
3579 expectKeyRepeatOnce(1 /*repeatCount*/);
3580 sendAndConsumeKeyDown(2 /* deviceId */);
3581 expectKeyRepeatOnce(1 /*repeatCount*/);
3582 // Stale key up from device 1.
3583 sendAndConsumeKeyUp(1 /* deviceId */);
3584 // Device 2 is still down, keep repeating
3585 expectKeyRepeatOnce(2 /*repeatCount*/);
3586 expectKeyRepeatOnce(3 /*repeatCount*/);
3587 // Device 2 key up
3588 sendAndConsumeKeyUp(2 /* deviceId */);
3589 mWindow->assertNoEvents();
3590}
3591
3592TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3593 sendAndConsumeKeyDown(1 /* deviceId */);
3594 expectKeyRepeatOnce(1 /*repeatCount*/);
3595 sendAndConsumeKeyDown(2 /* deviceId */);
3596 expectKeyRepeatOnce(1 /*repeatCount*/);
3597 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3598 sendAndConsumeKeyUp(2 /* deviceId */);
3599 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003600 mWindow->assertNoEvents();
3601}
3602
liushenxiang42232912021-05-21 20:24:09 +08003603TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3604 sendAndConsumeKeyDown(DEVICE_ID);
3605 expectKeyRepeatOnce(1 /*repeatCount*/);
3606 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3607 mDispatcher->notifyDeviceReset(&args);
3608 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3609 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3610 mWindow->assertNoEvents();
3611}
3612
Garfield Tan1c7bc862020-01-28 13:24:04 -08003613TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003614 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003615 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3616 InputEvent* repeatEvent = mWindow->consume();
3617 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3618 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3619 IdGenerator::getSource(repeatEvent->getId()));
3620 }
3621}
3622
3623TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003624 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003625
3626 std::unordered_set<int32_t> idSet;
3627 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3628 InputEvent* repeatEvent = mWindow->consume();
3629 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3630 int32_t id = repeatEvent->getId();
3631 EXPECT_EQ(idSet.end(), idSet.find(id));
3632 idSet.insert(id);
3633 }
3634}
3635
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003636/* Test InputDispatcher for MultiDisplay */
3637class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3638public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003639 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003640 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003641
Chris Yea209fde2020-07-22 13:54:51 -07003642 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003643 windowInPrimary =
3644 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003645
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003646 // Set focus window for primary display, but focused display would be second one.
3647 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003648 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003650 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003651 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003652
Chris Yea209fde2020-07-22 13:54:51 -07003653 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003654 windowInSecondary =
3655 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003656 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003657 // Set focus display to second one.
3658 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3659 // Set focus window for second display.
3660 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003661 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003662 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003663 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003664 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003665 }
3666
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003667 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003668 InputDispatcherTest::TearDown();
3669
Chris Yea209fde2020-07-22 13:54:51 -07003670 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003671 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003672 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673 windowInSecondary.clear();
3674 }
3675
3676protected:
Chris Yea209fde2020-07-22 13:54:51 -07003677 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003679 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680 sp<FakeWindowHandle> windowInSecondary;
3681};
3682
3683TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3684 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3686 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003688 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003689 windowInSecondary->assertNoEvents();
3690
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003691 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3694 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003695 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003696 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003697}
3698
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003699TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003700 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3702 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003703 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003704 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003705 windowInSecondary->assertNoEvents();
3706
3707 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003709 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003710 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003711 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003712
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003713 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003714 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003715
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003716 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003717 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3718 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003719
3720 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003721 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003722 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003723 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003724 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003725 windowInSecondary->assertNoEvents();
3726}
3727
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003728// Test per-display input monitors for motion event.
3729TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003730 FakeMonitorReceiver monitorInPrimary =
3731 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3732 FakeMonitorReceiver monitorInSecondary =
3733 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003734
3735 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3738 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003739 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003740 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003741 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003742 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003743
3744 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3746 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3747 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003748 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003749 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003750 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003751 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003752
3753 // Test inject a non-pointer motion event.
3754 // If specific a display, it will dispatch to the focused window of particular display,
3755 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3757 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3758 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003759 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003760 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003761 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003762 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003763}
3764
3765// Test per-display input monitors for key event.
3766TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003767 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003768 FakeMonitorReceiver monitorInPrimary =
3769 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3770 FakeMonitorReceiver monitorInSecondary =
3771 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003772
3773 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3775 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003776 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003777 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003778 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003779 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003780}
3781
Vishnu Nair958da932020-08-21 17:12:37 -07003782TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3783 sp<FakeWindowHandle> secondWindowInPrimary =
3784 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3785 secondWindowInPrimary->setFocusable(true);
3786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3787 setFocusedWindow(secondWindowInPrimary);
3788 windowInPrimary->consumeFocusEvent(false);
3789 secondWindowInPrimary->consumeFocusEvent(true);
3790
3791 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3793 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003794 windowInPrimary->assertNoEvents();
3795 windowInSecondary->assertNoEvents();
3796 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3797}
3798
Jackal Guof9696682018-10-05 12:23:23 +08003799class InputFilterTest : public InputDispatcherTest {
3800protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003801 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3802 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003803 NotifyMotionArgs motionArgs;
3804
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003805 motionArgs =
3806 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003807 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003808 motionArgs =
3809 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003810 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003811 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003812 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003813 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3814 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003815 } else {
3816 mFakePolicy->assertFilterInputEventWasNotCalled();
3817 }
3818 }
3819
3820 void testNotifyKey(bool expectToBeFiltered) {
3821 NotifyKeyArgs keyArgs;
3822
3823 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3824 mDispatcher->notifyKey(&keyArgs);
3825 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3826 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003827 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003828
3829 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003830 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003831 } else {
3832 mFakePolicy->assertFilterInputEventWasNotCalled();
3833 }
3834 }
3835};
3836
3837// Test InputFilter for MotionEvent
3838TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3839 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3840 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3841 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3842
3843 // Enable InputFilter
3844 mDispatcher->setInputFilterEnabled(true);
3845 // Test touch on both primary and second display, and check if both events are filtered.
3846 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3847 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3848
3849 // Disable InputFilter
3850 mDispatcher->setInputFilterEnabled(false);
3851 // Test touch on both primary and second display, and check if both events aren't filtered.
3852 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3853 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3854}
3855
3856// Test InputFilter for KeyEvent
3857TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3858 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3859 testNotifyKey(/*expectToBeFiltered*/ false);
3860
3861 // Enable InputFilter
3862 mDispatcher->setInputFilterEnabled(true);
3863 // Send a key event, and check if it is filtered.
3864 testNotifyKey(/*expectToBeFiltered*/ true);
3865
3866 // Disable InputFilter
3867 mDispatcher->setInputFilterEnabled(false);
3868 // Send a key event, and check if it isn't filtered.
3869 testNotifyKey(/*expectToBeFiltered*/ false);
3870}
3871
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003872// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3873// logical display coordinate space.
3874TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3875 ui::Transform firstDisplayTransform;
3876 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3877 ui::Transform secondDisplayTransform;
3878 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3879
3880 std::vector<gui::DisplayInfo> displayInfos(2);
3881 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3882 displayInfos[0].transform = firstDisplayTransform;
3883 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3884 displayInfos[1].transform = secondDisplayTransform;
3885
3886 mDispatcher->onWindowInfosChanged({}, displayInfos);
3887
3888 // Enable InputFilter
3889 mDispatcher->setInputFilterEnabled(true);
3890
3891 // Ensure the correct transforms are used for the displays.
3892 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3893 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3894}
3895
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003896class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3897protected:
3898 virtual void SetUp() override {
3899 InputDispatcherTest::SetUp();
3900
3901 /**
3902 * We don't need to enable input filter to test the injected event policy, but we enabled it
3903 * here to make the tests more realistic, since this policy only matters when inputfilter is
3904 * on.
3905 */
3906 mDispatcher->setInputFilterEnabled(true);
3907
3908 std::shared_ptr<InputApplicationHandle> application =
3909 std::make_shared<FakeApplicationHandle>();
3910 mWindow =
3911 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3912
3913 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3914 mWindow->setFocusable(true);
3915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3916 setFocusedWindow(mWindow);
3917 mWindow->consumeFocusEvent(true);
3918 }
3919
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003920 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3921 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003922 KeyEvent event;
3923
3924 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3925 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3926 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3927 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3928 const int32_t additionalPolicyFlags =
3929 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3931 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3932 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3933 policyFlags | additionalPolicyFlags));
3934
3935 InputEvent* received = mWindow->consume();
3936 ASSERT_NE(nullptr, received);
3937 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003938 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3939 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3940 ASSERT_EQ(flags, keyEvent.getFlags());
3941 }
3942
3943 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3944 int32_t flags) {
3945 MotionEvent event;
3946 PointerProperties pointerProperties[1];
3947 PointerCoords pointerCoords[1];
3948 pointerProperties[0].clear();
3949 pointerProperties[0].id = 0;
3950 pointerCoords[0].clear();
3951 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3952 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3953
3954 ui::Transform identityTransform;
3955 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3956 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3957 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3958 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3959 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003960 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003961 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003962 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3963
3964 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3966 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3967 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3968 policyFlags | additionalPolicyFlags));
3969
3970 InputEvent* received = mWindow->consume();
3971 ASSERT_NE(nullptr, received);
3972 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3973 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3974 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3975 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003976 }
3977
3978private:
3979 sp<FakeWindowHandle> mWindow;
3980};
3981
3982TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003983 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3984 // filter. Without it, the event will no different from a regularly injected event, and the
3985 // injected device id will be overwritten.
3986 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3987 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003988}
3989
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003990TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003991 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003992 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3993 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3994}
3995
3996TEST_F(InputFilterInjectionPolicyTest,
3997 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3998 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3999 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4000 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004001}
4002
4003TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4004 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004005 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004006}
4007
chaviwfd6d3512019-03-25 13:23:49 -07004008class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004009 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004010 InputDispatcherTest::SetUp();
4011
Chris Yea209fde2020-07-22 13:54:51 -07004012 std::shared_ptr<FakeApplicationHandle> application =
4013 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004014 mUnfocusedWindow =
4015 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004016 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4017 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4018 // window.
chaviw3277faf2021-05-19 16:45:23 -05004019 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004020
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004021 mFocusedWindow =
4022 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4023 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004024 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004025
4026 // Set focused application.
4027 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004028 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004029
4030 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004032 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004033 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004034 }
4035
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004036 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004037 InputDispatcherTest::TearDown();
4038
4039 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004040 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004041 }
4042
4043protected:
4044 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004045 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004046 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004047};
4048
4049// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4050// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4051// the onPointerDownOutsideFocus callback.
4052TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004054 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4055 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004056 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004057 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004058
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004059 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004060 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4061}
4062
4063// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4064// DOWN on the window that doesn't have focus. Ensure no window received the
4065// onPointerDownOutsideFocus callback.
4066TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004068 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004070 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004071
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004072 ASSERT_TRUE(mDispatcher->waitForIdle());
4073 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004074}
4075
4076// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4077// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4078TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4080 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004082 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004083
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004084 ASSERT_TRUE(mDispatcher->waitForIdle());
4085 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004086}
4087
4088// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4089// DOWN on the window that already has focus. Ensure no window received the
4090// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004091TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004093 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004094 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004095 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004096 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004097
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004098 ASSERT_TRUE(mDispatcher->waitForIdle());
4099 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004100}
4101
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004102// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4103// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4104TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4105 const MotionEvent event =
4106 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4107 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4108 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4109 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4110 .build();
4111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4113 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4114
4115 ASSERT_TRUE(mDispatcher->waitForIdle());
4116 mFakePolicy->assertOnPointerDownWasNotCalled();
4117 // Ensure that the unfocused window did not receive any FOCUS events.
4118 mUnfocusedWindow->assertNoEvents();
4119}
4120
chaviwaf87b3e2019-10-01 16:59:28 -07004121// These tests ensures we can send touch events to a single client when there are multiple input
4122// windows that point to the same client token.
4123class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4124 virtual void SetUp() override {
4125 InputDispatcherTest::SetUp();
4126
Chris Yea209fde2020-07-22 13:54:51 -07004127 std::shared_ptr<FakeApplicationHandle> application =
4128 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004129 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4130 ADISPLAY_ID_DEFAULT);
4131 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4132 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004133 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004134 mWindow1->setFrame(Rect(0, 0, 100, 100));
4135
4136 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4137 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004138 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004139 mWindow2->setFrame(Rect(100, 100, 200, 200));
4140
Arthur Hung72d8dc32020-03-28 00:48:39 +00004141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004142 }
4143
4144protected:
4145 sp<FakeWindowHandle> mWindow1;
4146 sp<FakeWindowHandle> mWindow2;
4147
4148 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004149 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004150 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4151 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004152 }
4153
4154 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4155 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004156 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004157 InputEvent* event = window->consume();
4158
4159 ASSERT_NE(nullptr, event) << name.c_str()
4160 << ": consumer should have returned non-NULL event.";
4161
4162 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4163 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4164 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4165
4166 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004167 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004168
4169 for (size_t i = 0; i < points.size(); i++) {
4170 float expectedX = points[i].x;
4171 float expectedY = points[i].y;
4172
4173 EXPECT_EQ(expectedX, motionEvent.getX(i))
4174 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4175 << ", got " << motionEvent.getX(i);
4176 EXPECT_EQ(expectedY, motionEvent.getY(i))
4177 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4178 << ", got " << motionEvent.getY(i);
4179 }
4180 }
chaviw9eaa22c2020-07-01 16:21:27 -07004181
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004182 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004183 std::vector<PointF> expectedPoints) {
4184 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4185 ADISPLAY_ID_DEFAULT, touchedPoints);
4186 mDispatcher->notifyMotion(&motionArgs);
4187
4188 // Always consume from window1 since it's the window that has the InputReceiver
4189 consumeMotionEvent(mWindow1, action, expectedPoints);
4190 }
chaviwaf87b3e2019-10-01 16:59:28 -07004191};
4192
4193TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4194 // Touch Window 1
4195 PointF touchedPoint = {10, 10};
4196 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004197 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004198
4199 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004200 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004201
4202 // Touch Window 2
4203 touchedPoint = {150, 150};
4204 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004205 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004206}
4207
chaviw9eaa22c2020-07-01 16:21:27 -07004208TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4209 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004210 mWindow2->setWindowScale(0.5f, 0.5f);
4211
4212 // Touch Window 1
4213 PointF touchedPoint = {10, 10};
4214 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004215 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004216 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004217 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004218
4219 // Touch Window 2
4220 touchedPoint = {150, 150};
4221 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004222 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4223 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004224
chaviw9eaa22c2020-07-01 16:21:27 -07004225 // Update the transform so rotation is set
4226 mWindow2->setWindowTransform(0, -1, 1, 0);
4227 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4228 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004229}
4230
chaviw9eaa22c2020-07-01 16:21:27 -07004231TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004232 mWindow2->setWindowScale(0.5f, 0.5f);
4233
4234 // Touch Window 1
4235 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4236 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004237 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004238
4239 // Touch Window 2
4240 int32_t actionPointerDown =
4241 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004242 touchedPoints.push_back(PointF{150, 150});
4243 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4244 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245
chaviw9eaa22c2020-07-01 16:21:27 -07004246 // Release Window 2
4247 int32_t actionPointerUp =
4248 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4249 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4250 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004251
chaviw9eaa22c2020-07-01 16:21:27 -07004252 // Update the transform so rotation is set for Window 2
4253 mWindow2->setWindowTransform(0, -1, 1, 0);
4254 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4255 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004256}
4257
chaviw9eaa22c2020-07-01 16:21:27 -07004258TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004259 mWindow2->setWindowScale(0.5f, 0.5f);
4260
4261 // Touch Window 1
4262 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4263 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004264 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004265
4266 // Touch Window 2
4267 int32_t actionPointerDown =
4268 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004269 touchedPoints.push_back(PointF{150, 150});
4270 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004271
chaviw9eaa22c2020-07-01 16:21:27 -07004272 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004273
4274 // Move both windows
4275 touchedPoints = {{20, 20}, {175, 175}};
4276 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4277 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4278
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004280
chaviw9eaa22c2020-07-01 16:21:27 -07004281 // Release Window 2
4282 int32_t actionPointerUp =
4283 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4284 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4285 expectedPoints.pop_back();
4286
4287 // Touch Window 2
4288 mWindow2->setWindowTransform(0, -1, 1, 0);
4289 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4290 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4291
4292 // Move both windows
4293 touchedPoints = {{20, 20}, {175, 175}};
4294 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4295 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4296
4297 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004298}
4299
4300TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4301 mWindow1->setWindowScale(0.5f, 0.5f);
4302
4303 // Touch Window 1
4304 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4305 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004306 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004307
4308 // Touch Window 2
4309 int32_t actionPointerDown =
4310 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004311 touchedPoints.push_back(PointF{150, 150});
4312 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004313
chaviw9eaa22c2020-07-01 16:21:27 -07004314 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004315
4316 // Move both windows
4317 touchedPoints = {{20, 20}, {175, 175}};
4318 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4319 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4320
chaviw9eaa22c2020-07-01 16:21:27 -07004321 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004322}
4323
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004324class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4325 virtual void SetUp() override {
4326 InputDispatcherTest::SetUp();
4327
Chris Yea209fde2020-07-22 13:54:51 -07004328 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004329 mApplication->setDispatchingTimeout(20ms);
4330 mWindow =
4331 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4332 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004333 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004334 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004335 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4336 // window.
chaviw3277faf2021-05-19 16:45:23 -05004337 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004338
4339 // Set focused application.
4340 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4341
4342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004343 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004344 mWindow->consumeFocusEvent(true);
4345 }
4346
4347 virtual void TearDown() override {
4348 InputDispatcherTest::TearDown();
4349 mWindow.clear();
4350 }
4351
4352protected:
Chris Yea209fde2020-07-22 13:54:51 -07004353 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004354 sp<FakeWindowHandle> mWindow;
4355 static constexpr PointF WINDOW_LOCATION = {20, 20};
4356
4357 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004359 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4360 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004362 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4363 WINDOW_LOCATION));
4364 }
4365};
4366
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004367// Send a tap and respond, which should not cause an ANR.
4368TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4369 tapOnWindow();
4370 mWindow->consumeMotionDown();
4371 mWindow->consumeMotionUp();
4372 ASSERT_TRUE(mDispatcher->waitForIdle());
4373 mFakePolicy->assertNotifyAnrWasNotCalled();
4374}
4375
4376// Send a regular key and respond, which should not cause an ANR.
4377TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004379 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4380 ASSERT_TRUE(mDispatcher->waitForIdle());
4381 mFakePolicy->assertNotifyAnrWasNotCalled();
4382}
4383
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004384TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4385 mWindow->setFocusable(false);
4386 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4387 mWindow->consumeFocusEvent(false);
4388
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004389 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004390 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004391 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4392 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004394 // Key will not go to window because we have no focused window.
4395 // The 'no focused window' ANR timer should start instead.
4396
4397 // Now, the focused application goes away.
4398 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4399 // The key should get dropped and there should be no ANR.
4400
4401 ASSERT_TRUE(mDispatcher->waitForIdle());
4402 mFakePolicy->assertNotifyAnrWasNotCalled();
4403}
4404
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004406// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4407// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004408TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004410 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4411 WINDOW_LOCATION));
4412
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004413 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4414 ASSERT_TRUE(sequenceNum);
4415 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004416 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004417
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004418 mWindow->finishEvent(*sequenceNum);
4419 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4420 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004422 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004423}
4424
4425// Send a key to the app and have the app not respond right away.
4426TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4427 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004429 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4430 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004431 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004432 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004433 ASSERT_TRUE(mDispatcher->waitForIdle());
4434}
4435
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436// We have a focused application, but no focused window
4437TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004438 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4440 mWindow->consumeFocusEvent(false);
4441
4442 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4445 WINDOW_LOCATION));
4446 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4447 mDispatcher->waitForIdle();
4448 mFakePolicy->assertNotifyAnrWasNotCalled();
4449
4450 // Once a focused event arrives, we get an ANR for this application
4451 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4452 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004453 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004454 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004455 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004456 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004458 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459 ASSERT_TRUE(mDispatcher->waitForIdle());
4460}
4461
4462// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004463// Make sure that we don't notify policy twice about the same ANR.
4464TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004465 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4467 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004468
4469 // Once a focused event arrives, we get an ANR for this application
4470 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4471 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004472 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004474 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476 const std::chrono::duration appTimeout =
4477 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004478 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004480 std::this_thread::sleep_for(appTimeout);
4481 // ANR should not be raised again. It is up to policy to do that if it desires.
4482 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004484 // If we now get a focused window, the ANR should stop, but the policy handles that via
4485 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486 ASSERT_TRUE(mDispatcher->waitForIdle());
4487}
4488
4489// We have a focused application, but no focused window
4490TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004491 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4493 mWindow->consumeFocusEvent(false);
4494
4495 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004496 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004497 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4499 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500
4501 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004502 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004503
4504 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004505 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004506 ASSERT_TRUE(mDispatcher->waitForIdle());
4507 mWindow->assertNoEvents();
4508}
4509
4510/**
4511 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4512 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4513 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4514 * the ANR mechanism should still work.
4515 *
4516 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4517 * DOWN event, while not responding on the second one.
4518 */
4519TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4520 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4521 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4522 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4523 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4524 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004525 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004526
4527 // Now send ACTION_UP, with identical timestamp
4528 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4529 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4530 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4531 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004532 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004533
4534 // We have now sent down and up. Let's consume first event and then ANR on the second.
4535 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4536 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004537 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538}
4539
4540// If an app is not responding to a key event, gesture monitors should continue to receive
4541// new motion events
4542TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4543 FakeMonitorReceiver monitor =
4544 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4545 true /*isGestureMonitor*/);
4546
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4548 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004551
4552 // Stuck on the ACTION_UP
4553 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004554 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 // New tap will go to the gesture monitor, but not to the window
4557 tapOnWindow();
4558 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4559 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4560
4561 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4562 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004563 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564 mWindow->assertNoEvents();
4565 monitor.assertNoEvents();
4566}
4567
4568// If an app is not responding to a motion event, gesture monitors should continue to receive
4569// new motion events
4570TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4571 FakeMonitorReceiver monitor =
4572 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4573 true /*isGestureMonitor*/);
4574
4575 tapOnWindow();
4576 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4577 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4578
4579 mWindow->consumeMotionDown();
4580 // Stuck on the ACTION_UP
4581 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004582 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583
4584 // New tap will go to the gesture monitor, but not to the window
4585 tapOnWindow();
4586 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4587 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4588
4589 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4590 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004591 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592 mWindow->assertNoEvents();
4593 monitor.assertNoEvents();
4594}
4595
4596// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4597// process events, you don't get an anr. When the window later becomes unresponsive again, you
4598// get an ANR again.
4599// 1. tap -> block on ACTION_UP -> receive ANR
4600// 2. consume all pending events (= queue becomes healthy again)
4601// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4602TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4603 tapOnWindow();
4604
4605 mWindow->consumeMotionDown();
4606 // Block on ACTION_UP
4607 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004608 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4610 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004611 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612 mWindow->assertNoEvents();
4613
4614 tapOnWindow();
4615 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004616 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 mWindow->consumeMotionUp();
4618
4619 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004620 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004621 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 mWindow->assertNoEvents();
4623}
4624
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004625// If a connection remains unresponsive for a while, make sure policy is only notified once about
4626// it.
4627TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4630 WINDOW_LOCATION));
4631
4632 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004633 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004634 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004635 // 'notifyConnectionUnresponsive' should only be called once per connection
4636 mFakePolicy->assertNotifyAnrWasNotCalled();
4637 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004638 mWindow->consumeMotionDown();
4639 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4640 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4641 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004642 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004643 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004644 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645}
4646
4647/**
4648 * If a window is processing a motion event, and then a key event comes in, the key event should
4649 * not to to the focused window until the motion is processed.
4650 *
4651 * Warning!!!
4652 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4653 * and the injection timeout that we specify when injecting the key.
4654 * We must have the injection timeout (10ms) be smaller than
4655 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4656 *
4657 * If that value changes, this test should also change.
4658 */
4659TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4660 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4662
4663 tapOnWindow();
4664 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4665 ASSERT_TRUE(downSequenceNum);
4666 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4667 ASSERT_TRUE(upSequenceNum);
4668 // Don't finish the events yet, and send a key
4669 // Injection will "succeed" because we will eventually give up and send the key to the focused
4670 // window even if motions are still being processed. But because the injection timeout is short,
4671 // we will receive INJECTION_TIMED_OUT as the result.
4672
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004673 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004675 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4676 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677 // Key will not be sent to the window, yet, because the window is still processing events
4678 // and the key remains pending, waiting for the touch events to be processed
4679 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4680 ASSERT_FALSE(keySequenceNum);
4681
4682 std::this_thread::sleep_for(500ms);
4683 // if we wait long enough though, dispatcher will give up, and still send the key
4684 // to the focused window, even though we have not yet finished the motion event
4685 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4686 mWindow->finishEvent(*downSequenceNum);
4687 mWindow->finishEvent(*upSequenceNum);
4688}
4689
4690/**
4691 * If a window is processing a motion event, and then a key event comes in, the key event should
4692 * not go to the focused window until the motion is processed.
4693 * If then a new motion comes in, then the pending key event should be going to the currently
4694 * focused window right away.
4695 */
4696TEST_F(InputDispatcherSingleWindowAnr,
4697 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4698 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4700
4701 tapOnWindow();
4702 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4703 ASSERT_TRUE(downSequenceNum);
4704 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4705 ASSERT_TRUE(upSequenceNum);
4706 // Don't finish the events yet, and send a key
4707 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004710 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004711 // At this point, key is still pending, and should not be sent to the application yet.
4712 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4713 ASSERT_FALSE(keySequenceNum);
4714
4715 // Now tap down again. It should cause the pending key to go to the focused window right away.
4716 tapOnWindow();
4717 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4718 // the other events yet. We can finish events in any order.
4719 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4720 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4721 mWindow->consumeMotionDown();
4722 mWindow->consumeMotionUp();
4723 mWindow->assertNoEvents();
4724}
4725
4726class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4727 virtual void SetUp() override {
4728 InputDispatcherTest::SetUp();
4729
Chris Yea209fde2020-07-22 13:54:51 -07004730 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731 mApplication->setDispatchingTimeout(10ms);
4732 mUnfocusedWindow =
4733 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4734 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4735 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4736 // window.
4737 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004738 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4739 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4740 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741
4742 mFocusedWindow =
4743 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004744 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004746 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747
4748 // Set focused application.
4749 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004750 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004751
4752 // Expect one focus window exist in display.
4753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004754 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755 mFocusedWindow->consumeFocusEvent(true);
4756 }
4757
4758 virtual void TearDown() override {
4759 InputDispatcherTest::TearDown();
4760
4761 mUnfocusedWindow.clear();
4762 mFocusedWindow.clear();
4763 }
4764
4765protected:
Chris Yea209fde2020-07-22 13:54:51 -07004766 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004767 sp<FakeWindowHandle> mUnfocusedWindow;
4768 sp<FakeWindowHandle> mFocusedWindow;
4769 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4770 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4771 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4772
4773 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4774
4775 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4776
4777private:
4778 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4781 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004782 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004783 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4784 location));
4785 }
4786};
4787
4788// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4789// should be ANR'd first.
4790TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4793 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004794 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795 mFocusedWindow->consumeMotionDown();
4796 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4797 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4798 // We consumed all events, so no ANR
4799 ASSERT_TRUE(mDispatcher->waitForIdle());
4800 mFakePolicy->assertNotifyAnrWasNotCalled();
4801
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4804 FOCUSED_WINDOW_LOCATION));
4805 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4806 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807
4808 const std::chrono::duration timeout =
4809 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004810 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004811 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4812 // sequence to make it consistent
4813 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004815 mFocusedWindow->consumeMotionDown();
4816 // This cancel is generated because the connection was unresponsive
4817 mFocusedWindow->consumeMotionCancel();
4818 mFocusedWindow->assertNoEvents();
4819 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004821 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004822 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823}
4824
4825// If we have 2 windows with identical timeouts that are both unresponsive,
4826// it doesn't matter which order they should have ANR.
4827// But we should receive ANR for both.
4828TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4829 // Set the timeout for unfocused window to match the focused window
4830 mUnfocusedWindow->setDispatchingTimeout(10ms);
4831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4832
4833 tapOnFocusedWindow();
4834 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004835 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4836 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837
4838 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004839 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4840 mFocusedWindow->getToken() == anrConnectionToken2);
4841 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4842 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843
4844 ASSERT_TRUE(mDispatcher->waitForIdle());
4845 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004846
4847 mFocusedWindow->consumeMotionDown();
4848 mFocusedWindow->consumeMotionUp();
4849 mUnfocusedWindow->consumeMotionOutside();
4850
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004851 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4852 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004853
4854 // Both applications should be marked as responsive, in any order
4855 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4856 mFocusedWindow->getToken() == responsiveToken2);
4857 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4858 mUnfocusedWindow->getToken() == responsiveToken2);
4859 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860}
4861
4862// If a window is already not responding, the second tap on the same window should be ignored.
4863// We should also log an error to account for the dropped event (not tested here).
4864// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4865TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4866 tapOnFocusedWindow();
4867 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4868 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4869 // Receive the events, but don't respond
4870 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4871 ASSERT_TRUE(downEventSequenceNum);
4872 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4873 ASSERT_TRUE(upEventSequenceNum);
4874 const std::chrono::duration timeout =
4875 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004876 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877
4878 // Tap once again
4879 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004880 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4882 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4885 FOCUSED_WINDOW_LOCATION));
4886 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4887 // valid touch target
4888 mUnfocusedWindow->assertNoEvents();
4889
4890 // Consume the first tap
4891 mFocusedWindow->finishEvent(*downEventSequenceNum);
4892 mFocusedWindow->finishEvent(*upEventSequenceNum);
4893 ASSERT_TRUE(mDispatcher->waitForIdle());
4894 // The second tap did not go to the focused window
4895 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004896 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004897 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 mFakePolicy->assertNotifyAnrWasNotCalled();
4899}
4900
4901// If you tap outside of all windows, there will not be ANR
4902TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004903 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4905 LOCATION_OUTSIDE_ALL_WINDOWS));
4906 ASSERT_TRUE(mDispatcher->waitForIdle());
4907 mFakePolicy->assertNotifyAnrWasNotCalled();
4908}
4909
4910// Since the focused window is paused, tapping on it should not produce any events
4911TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4912 mFocusedWindow->setPaused(true);
4913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004915 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4917 FOCUSED_WINDOW_LOCATION));
4918
4919 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4920 ASSERT_TRUE(mDispatcher->waitForIdle());
4921 // Should not ANR because the window is paused, and touches shouldn't go to it
4922 mFakePolicy->assertNotifyAnrWasNotCalled();
4923
4924 mFocusedWindow->assertNoEvents();
4925 mUnfocusedWindow->assertNoEvents();
4926}
4927
4928/**
4929 * If a window is processing a motion event, and then a key event comes in, the key event should
4930 * not to to the focused window until the motion is processed.
4931 * If a different window becomes focused at this time, the key should go to that window instead.
4932 *
4933 * Warning!!!
4934 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4935 * and the injection timeout that we specify when injecting the key.
4936 * We must have the injection timeout (10ms) be smaller than
4937 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4938 *
4939 * If that value changes, this test should also change.
4940 */
4941TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4942 // Set a long ANR timeout to prevent it from triggering
4943 mFocusedWindow->setDispatchingTimeout(2s);
4944 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4945
4946 tapOnUnfocusedWindow();
4947 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4948 ASSERT_TRUE(downSequenceNum);
4949 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4950 ASSERT_TRUE(upSequenceNum);
4951 // Don't finish the events yet, and send a key
4952 // Injection will succeed because we will eventually give up and send the key to the focused
4953 // window even if motions are still being processed.
4954
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004957 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959 // Key will not be sent to the window, yet, because the window is still processing events
4960 // and the key remains pending, waiting for the touch events to be processed
4961 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4962 ASSERT_FALSE(keySequenceNum);
4963
4964 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004965 mFocusedWindow->setFocusable(false);
4966 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004967 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004968 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004969
4970 // Focus events should precede the key events
4971 mUnfocusedWindow->consumeFocusEvent(true);
4972 mFocusedWindow->consumeFocusEvent(false);
4973
4974 // Finish the tap events, which should unblock dispatcher
4975 mUnfocusedWindow->finishEvent(*downSequenceNum);
4976 mUnfocusedWindow->finishEvent(*upSequenceNum);
4977
4978 // Now that all queues are cleared and no backlog in the connections, the key event
4979 // can finally go to the newly focused "mUnfocusedWindow".
4980 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4981 mFocusedWindow->assertNoEvents();
4982 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004983 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984}
4985
4986// When the touch stream is split across 2 windows, and one of them does not respond,
4987// then ANR should be raised and the touch should be canceled for the unresponsive window.
4988// The other window should not be affected by that.
4989TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4990 // Touch Window 1
4991 NotifyMotionArgs motionArgs =
4992 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4993 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4994 mDispatcher->notifyMotion(&motionArgs);
4995 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4996 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4997
4998 // Touch Window 2
4999 int32_t actionPointerDown =
5000 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5001
5002 motionArgs =
5003 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5004 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5005 mDispatcher->notifyMotion(&motionArgs);
5006
5007 const std::chrono::duration timeout =
5008 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005009 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005010
5011 mUnfocusedWindow->consumeMotionDown();
5012 mFocusedWindow->consumeMotionDown();
5013 // Focused window may or may not receive ACTION_MOVE
5014 // But it should definitely receive ACTION_CANCEL due to the ANR
5015 InputEvent* event;
5016 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5017 ASSERT_TRUE(moveOrCancelSequenceNum);
5018 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5019 ASSERT_NE(nullptr, event);
5020 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5021 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5022 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5023 mFocusedWindow->consumeMotionCancel();
5024 } else {
5025 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5026 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005027 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005028 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005029
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005030 mUnfocusedWindow->assertNoEvents();
5031 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005032 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005033}
5034
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005035/**
5036 * If we have no focused window, and a key comes in, we start the ANR timer.
5037 * The focused application should add a focused window before the timer runs out to prevent ANR.
5038 *
5039 * If the user touches another application during this time, the key should be dropped.
5040 * Next, if a new focused window comes in, without toggling the focused application,
5041 * then no ANR should occur.
5042 *
5043 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5044 * but in some cases the policy may not update the focused application.
5045 */
5046TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5047 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5048 std::make_shared<FakeApplicationHandle>();
5049 focusedApplication->setDispatchingTimeout(60ms);
5050 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5051 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5052 mFocusedWindow->setFocusable(false);
5053
5054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5055 mFocusedWindow->consumeFocusEvent(false);
5056
5057 // Send a key. The ANR timer should start because there is no focused window.
5058 // 'focusedApplication' will get blamed if this timer completes.
5059 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005060 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005061 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005062 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5063 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005065
5066 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5067 // then the injected touches won't cause the focused event to get dropped.
5068 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5069 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5070 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5071 // For this test, it means that the key would get delivered to the window once it becomes
5072 // focused.
5073 std::this_thread::sleep_for(10ms);
5074
5075 // Touch unfocused window. This should force the pending key to get dropped.
5076 NotifyMotionArgs motionArgs =
5077 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5078 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5079 mDispatcher->notifyMotion(&motionArgs);
5080
5081 // We do not consume the motion right away, because that would require dispatcher to first
5082 // process (== drop) the key event, and by that time, ANR will be raised.
5083 // Set the focused window first.
5084 mFocusedWindow->setFocusable(true);
5085 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5086 setFocusedWindow(mFocusedWindow);
5087 mFocusedWindow->consumeFocusEvent(true);
5088 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5089 // to another application. This could be a bug / behaviour in the policy.
5090
5091 mUnfocusedWindow->consumeMotionDown();
5092
5093 ASSERT_TRUE(mDispatcher->waitForIdle());
5094 // Should not ANR because we actually have a focused window. It was just added too slowly.
5095 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5096}
5097
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005098// These tests ensure we cannot send touch events to a window that's positioned behind a window
5099// that has feature NO_INPUT_CHANNEL.
5100// Layout:
5101// Top (closest to user)
5102// mNoInputWindow (above all windows)
5103// mBottomWindow
5104// Bottom (furthest from user)
5105class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5106 virtual void SetUp() override {
5107 InputDispatcherTest::SetUp();
5108
5109 mApplication = std::make_shared<FakeApplicationHandle>();
5110 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5111 "Window without input channel", ADISPLAY_ID_DEFAULT,
5112 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5113
chaviw3277faf2021-05-19 16:45:23 -05005114 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005115 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5116 // It's perfectly valid for this window to not have an associated input channel
5117
5118 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5119 ADISPLAY_ID_DEFAULT);
5120 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5121
5122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5123 }
5124
5125protected:
5126 std::shared_ptr<FakeApplicationHandle> mApplication;
5127 sp<FakeWindowHandle> mNoInputWindow;
5128 sp<FakeWindowHandle> mBottomWindow;
5129};
5130
5131TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5132 PointF touchedPoint = {10, 10};
5133
5134 NotifyMotionArgs motionArgs =
5135 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5136 ADISPLAY_ID_DEFAULT, {touchedPoint});
5137 mDispatcher->notifyMotion(&motionArgs);
5138
5139 mNoInputWindow->assertNoEvents();
5140 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5141 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5142 // and therefore should prevent mBottomWindow from receiving touches
5143 mBottomWindow->assertNoEvents();
5144}
5145
5146/**
5147 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5148 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5149 */
5150TEST_F(InputDispatcherMultiWindowOcclusionTests,
5151 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5152 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5153 "Window with input channel and NO_INPUT_CHANNEL",
5154 ADISPLAY_ID_DEFAULT);
5155
chaviw3277faf2021-05-19 16:45:23 -05005156 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005157 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5158 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5159
5160 PointF touchedPoint = {10, 10};
5161
5162 NotifyMotionArgs motionArgs =
5163 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5164 ADISPLAY_ID_DEFAULT, {touchedPoint});
5165 mDispatcher->notifyMotion(&motionArgs);
5166
5167 mNoInputWindow->assertNoEvents();
5168 mBottomWindow->assertNoEvents();
5169}
5170
Vishnu Nair958da932020-08-21 17:12:37 -07005171class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5172protected:
5173 std::shared_ptr<FakeApplicationHandle> mApp;
5174 sp<FakeWindowHandle> mWindow;
5175 sp<FakeWindowHandle> mMirror;
5176
5177 virtual void SetUp() override {
5178 InputDispatcherTest::SetUp();
5179 mApp = std::make_shared<FakeApplicationHandle>();
5180 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5181 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5182 mWindow->getToken());
5183 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5184 mWindow->setFocusable(true);
5185 mMirror->setFocusable(true);
5186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5187 }
5188};
5189
5190TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5191 // Request focus on a mirrored window
5192 setFocusedWindow(mMirror);
5193
5194 // window gets focused
5195 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5197 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005198 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5199}
5200
5201// A focused & mirrored window remains focused only if the window and its mirror are both
5202// focusable.
5203TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5204 setFocusedWindow(mMirror);
5205
5206 // window gets focused
5207 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5209 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005210 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5212 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005213 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5214
5215 mMirror->setFocusable(false);
5216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5217
5218 // window loses focus since one of the windows associated with the token in not focusable
5219 mWindow->consumeFocusEvent(false);
5220
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005221 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5222 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005223 mWindow->assertNoEvents();
5224}
5225
5226// A focused & mirrored window remains focused until the window and its mirror both become
5227// invisible.
5228TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5229 setFocusedWindow(mMirror);
5230
5231 // window gets focused
5232 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5234 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005235 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5237 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005238 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5239
5240 mMirror->setVisible(false);
5241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5242
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5244 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005245 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005246 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5247 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005248 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5249
5250 mWindow->setVisible(false);
5251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5252
5253 // window loses focus only after all windows associated with the token become invisible.
5254 mWindow->consumeFocusEvent(false);
5255
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005256 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5257 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005258 mWindow->assertNoEvents();
5259}
5260
5261// A focused & mirrored window remains focused until both windows are removed.
5262TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5263 setFocusedWindow(mMirror);
5264
5265 // window gets focused
5266 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5268 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005269 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5271 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005272 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5273
5274 // single window is removed but the window token remains focused
5275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5276
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5278 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005279 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005280 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5281 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005282 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5283
5284 // Both windows are removed
5285 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5286 mWindow->consumeFocusEvent(false);
5287
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005288 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5289 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005290 mWindow->assertNoEvents();
5291}
5292
5293// Focus request can be pending until one window becomes visible.
5294TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5295 // Request focus on an invisible mirror.
5296 mWindow->setVisible(false);
5297 mMirror->setVisible(false);
5298 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5299 setFocusedWindow(mMirror);
5300
5301 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005303 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005305
5306 mMirror->setVisible(true);
5307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5308
5309 // window gets focused
5310 mWindow->consumeFocusEvent(true);
5311 // window gets the pending key event
5312 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5313}
Prabir Pradhan99987712020-11-10 18:43:05 -08005314
5315class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5316protected:
5317 std::shared_ptr<FakeApplicationHandle> mApp;
5318 sp<FakeWindowHandle> mWindow;
5319 sp<FakeWindowHandle> mSecondWindow;
5320
5321 void SetUp() override {
5322 InputDispatcherTest::SetUp();
5323 mApp = std::make_shared<FakeApplicationHandle>();
5324 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5325 mWindow->setFocusable(true);
5326 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5327 mSecondWindow->setFocusable(true);
5328
5329 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5331
5332 setFocusedWindow(mWindow);
5333 mWindow->consumeFocusEvent(true);
5334 }
5335
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005336 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5337 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005338 mDispatcher->notifyPointerCaptureChanged(&args);
5339 }
5340
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005341 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5342 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005343 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005344 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5345 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005346 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005347 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005348 }
5349};
5350
5351TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5352 // Ensure that capture cannot be obtained for unfocused windows.
5353 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5354 mFakePolicy->assertSetPointerCaptureNotCalled();
5355 mSecondWindow->assertNoEvents();
5356
5357 // Ensure that capture can be enabled from the focus window.
5358 requestAndVerifyPointerCapture(mWindow, true);
5359
5360 // Ensure that capture cannot be disabled from a window that does not have capture.
5361 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5362 mFakePolicy->assertSetPointerCaptureNotCalled();
5363
5364 // Ensure that capture can be disabled from the window with capture.
5365 requestAndVerifyPointerCapture(mWindow, false);
5366}
5367
5368TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005369 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005370
5371 setFocusedWindow(mSecondWindow);
5372
5373 // Ensure that the capture disabled event was sent first.
5374 mWindow->consumeCaptureEvent(false);
5375 mWindow->consumeFocusEvent(false);
5376 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005377 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005378
5379 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005380 notifyPointerCaptureChanged({});
5381 notifyPointerCaptureChanged(request);
5382 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005383 mWindow->assertNoEvents();
5384 mSecondWindow->assertNoEvents();
5385 mFakePolicy->assertSetPointerCaptureNotCalled();
5386}
5387
5388TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005389 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005390
5391 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005392 notifyPointerCaptureChanged({});
5393 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005394
5395 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005396 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005397 mWindow->consumeCaptureEvent(false);
5398 mWindow->assertNoEvents();
5399}
5400
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005401TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5402 requestAndVerifyPointerCapture(mWindow, true);
5403
5404 // The first window loses focus.
5405 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005406 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005407 mWindow->consumeCaptureEvent(false);
5408
5409 // Request Pointer Capture from the second window before the notification from InputReader
5410 // arrives.
5411 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005412 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005413
5414 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005415 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005416
5417 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005418 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005419
5420 mSecondWindow->consumeFocusEvent(true);
5421 mSecondWindow->consumeCaptureEvent(true);
5422}
5423
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005424TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5425 // App repeatedly enables and disables capture.
5426 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5427 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5428 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5429 mFakePolicy->assertSetPointerCaptureCalled(false);
5430 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5431 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5432
5433 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5434 // first request is now stale, this should do nothing.
5435 notifyPointerCaptureChanged(firstRequest);
5436 mWindow->assertNoEvents();
5437
5438 // InputReader notifies that the second request was enabled.
5439 notifyPointerCaptureChanged(secondRequest);
5440 mWindow->consumeCaptureEvent(true);
5441}
5442
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005443class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5444protected:
5445 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005446
5447 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5448 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5449
5450 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5451 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5452
5453 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5454 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5455 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5456 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5457 MAXIMUM_OBSCURING_OPACITY);
5458
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005459 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005460 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005461 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005462
5463 sp<FakeWindowHandle> mTouchWindow;
5464
5465 virtual void SetUp() override {
5466 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005467 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005468 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5469 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5470 }
5471
5472 virtual void TearDown() override {
5473 InputDispatcherTest::TearDown();
5474 mTouchWindow.clear();
5475 }
5476
chaviw3277faf2021-05-19 16:45:23 -05005477 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5478 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005479 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005480 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005481 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005482 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005483 return window;
5484 }
5485
5486 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5487 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5488 sp<FakeWindowHandle> window =
5489 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5490 // Generate an arbitrary PID based on the UID
5491 window->setOwnerInfo(1777 + (uid % 10000), uid);
5492 return window;
5493 }
5494
5495 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5496 NotifyMotionArgs args =
5497 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5498 ADISPLAY_ID_DEFAULT, points);
5499 mDispatcher->notifyMotion(&args);
5500 }
5501};
5502
5503TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005504 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005505 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005507
5508 touch();
5509
5510 mTouchWindow->assertNoEvents();
5511}
5512
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005513TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005514 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5515 const sp<FakeWindowHandle>& w =
5516 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5518
5519 touch();
5520
5521 mTouchWindow->assertNoEvents();
5522}
5523
5524TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005525 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5526 const sp<FakeWindowHandle>& w =
5527 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5529
5530 touch();
5531
5532 w->assertNoEvents();
5533}
5534
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005535TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005536 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005538
5539 touch();
5540
5541 mTouchWindow->consumeAnyMotionDown();
5542}
5543
5544TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005545 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005546 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005547 w->setFrame(Rect(0, 0, 50, 50));
5548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005549
5550 touch({PointF{100, 100}});
5551
5552 mTouchWindow->consumeAnyMotionDown();
5553}
5554
5555TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005556 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005557 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5559
5560 touch();
5561
5562 mTouchWindow->consumeAnyMotionDown();
5563}
5564
5565TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5566 const sp<FakeWindowHandle>& w =
5567 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005569
5570 touch();
5571
5572 mTouchWindow->consumeAnyMotionDown();
5573}
5574
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005575TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5576 const sp<FakeWindowHandle>& w =
5577 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5579
5580 touch();
5581
5582 w->assertNoEvents();
5583}
5584
5585/**
5586 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5587 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5588 * window, the occluding window will still receive ACTION_OUTSIDE event.
5589 */
5590TEST_F(InputDispatcherUntrustedTouchesTest,
5591 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5592 const sp<FakeWindowHandle>& w =
5593 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005594 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5596
5597 touch();
5598
5599 w->consumeMotionOutside();
5600}
5601
5602TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5603 const sp<FakeWindowHandle>& w =
5604 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005605 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5607
5608 touch();
5609
5610 InputEvent* event = w->consume();
5611 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5612 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5613 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5614 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5615}
5616
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005617TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005618 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005619 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5620 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5622
5623 touch();
5624
5625 mTouchWindow->consumeAnyMotionDown();
5626}
5627
5628TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5629 const sp<FakeWindowHandle>& w =
5630 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5631 MAXIMUM_OBSCURING_OPACITY);
5632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005633
5634 touch();
5635
5636 mTouchWindow->consumeAnyMotionDown();
5637}
5638
5639TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005640 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005641 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5642 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5644
5645 touch();
5646
5647 mTouchWindow->assertNoEvents();
5648}
5649
5650TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5651 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5652 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005653 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5654 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005655 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005656 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5657 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5659
5660 touch();
5661
5662 mTouchWindow->assertNoEvents();
5663}
5664
5665TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5666 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5667 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005668 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5669 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005670 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005671 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5672 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5674
5675 touch();
5676
5677 mTouchWindow->consumeAnyMotionDown();
5678}
5679
5680TEST_F(InputDispatcherUntrustedTouchesTest,
5681 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5682 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005683 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5684 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005685 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005686 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5687 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005688 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5689
5690 touch();
5691
5692 mTouchWindow->consumeAnyMotionDown();
5693}
5694
5695TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5696 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005697 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5698 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005699 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005700 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5701 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005703
5704 touch();
5705
5706 mTouchWindow->assertNoEvents();
5707}
5708
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005709TEST_F(InputDispatcherUntrustedTouchesTest,
5710 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5711 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005712 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5713 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005714 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005715 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5716 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5718
5719 touch();
5720
5721 mTouchWindow->assertNoEvents();
5722}
5723
5724TEST_F(InputDispatcherUntrustedTouchesTest,
5725 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5726 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005727 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5728 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005729 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005730 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5731 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5733
5734 touch();
5735
5736 mTouchWindow->consumeAnyMotionDown();
5737}
5738
5739TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5740 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005741 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5742 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5744
5745 touch();
5746
5747 mTouchWindow->consumeAnyMotionDown();
5748}
5749
5750TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5751 const sp<FakeWindowHandle>& w =
5752 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5754
5755 touch();
5756
5757 mTouchWindow->consumeAnyMotionDown();
5758}
5759
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005760TEST_F(InputDispatcherUntrustedTouchesTest,
5761 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5762 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5763 const sp<FakeWindowHandle>& w =
5764 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5766
5767 touch();
5768
5769 mTouchWindow->assertNoEvents();
5770}
5771
5772TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5773 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5774 const sp<FakeWindowHandle>& w =
5775 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5777
5778 touch();
5779
5780 mTouchWindow->consumeAnyMotionDown();
5781}
5782
5783TEST_F(InputDispatcherUntrustedTouchesTest,
5784 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5785 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5786 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005787 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5788 OPACITY_ABOVE_THRESHOLD);
5789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5790
5791 touch();
5792
5793 mTouchWindow->consumeAnyMotionDown();
5794}
5795
5796TEST_F(InputDispatcherUntrustedTouchesTest,
5797 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5798 const sp<FakeWindowHandle>& w1 =
5799 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5800 OPACITY_BELOW_THRESHOLD);
5801 const sp<FakeWindowHandle>& w2 =
5802 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5803 OPACITY_BELOW_THRESHOLD);
5804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5805
5806 touch();
5807
5808 mTouchWindow->assertNoEvents();
5809}
5810
5811/**
5812 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5813 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5814 * (which alone would result in allowing touches) does not affect the blocking behavior.
5815 */
5816TEST_F(InputDispatcherUntrustedTouchesTest,
5817 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5818 const sp<FakeWindowHandle>& wB =
5819 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5820 OPACITY_BELOW_THRESHOLD);
5821 const sp<FakeWindowHandle>& wC =
5822 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5823 OPACITY_BELOW_THRESHOLD);
5824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5825
5826 touch();
5827
5828 mTouchWindow->assertNoEvents();
5829}
5830
5831/**
5832 * This test is testing that a window from a different UID but with same application token doesn't
5833 * block the touch. Apps can share the application token for close UI collaboration for example.
5834 */
5835TEST_F(InputDispatcherUntrustedTouchesTest,
5836 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5837 const sp<FakeWindowHandle>& w =
5838 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5839 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005840 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5841
5842 touch();
5843
5844 mTouchWindow->consumeAnyMotionDown();
5845}
5846
arthurhungb89ccb02020-12-30 16:19:01 +08005847class InputDispatcherDragTests : public InputDispatcherTest {
5848protected:
5849 std::shared_ptr<FakeApplicationHandle> mApp;
5850 sp<FakeWindowHandle> mWindow;
5851 sp<FakeWindowHandle> mSecondWindow;
5852 sp<FakeWindowHandle> mDragWindow;
5853
5854 void SetUp() override {
5855 InputDispatcherTest::SetUp();
5856 mApp = std::make_shared<FakeApplicationHandle>();
5857 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5858 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005859 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005860
5861 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5862 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005863 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005864
5865 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5867 }
5868
5869 // Start performing drag, we will create a drag window and transfer touch to it.
5870 void performDrag() {
5871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5872 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5873 {50, 50}))
5874 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5875
5876 // Window should receive motion event.
5877 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5878
5879 // The drag window covers the entire display
5880 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5881 mDispatcher->setInputWindows(
5882 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5883
5884 // Transfer touch focus to the drag window
5885 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5886 true /* isDragDrop */);
5887 mWindow->consumeMotionCancel();
5888 mDragWindow->consumeMotionDown();
5889 }
arthurhung6d4bed92021-03-17 11:59:33 +08005890
5891 // Start performing drag, we will create a drag window and transfer touch to it.
5892 void performStylusDrag() {
5893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5894 injectMotionEvent(mDispatcher,
5895 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5896 AINPUT_SOURCE_STYLUS)
5897 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5898 .pointer(PointerBuilder(0,
5899 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5900 .x(50)
5901 .y(50))
5902 .build()));
5903 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5904
5905 // The drag window covers the entire display
5906 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5907 mDispatcher->setInputWindows(
5908 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5909
5910 // Transfer touch focus to the drag window
5911 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5912 true /* isDragDrop */);
5913 mWindow->consumeMotionCancel();
5914 mDragWindow->consumeMotionDown();
5915 }
arthurhungb89ccb02020-12-30 16:19:01 +08005916};
5917
5918TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5919 performDrag();
5920
5921 // Move on window.
5922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5923 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5924 ADISPLAY_ID_DEFAULT, {50, 50}))
5925 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5926 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5927 mWindow->consumeDragEvent(false, 50, 50);
5928 mSecondWindow->assertNoEvents();
5929
5930 // Move to another window.
5931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5932 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5933 ADISPLAY_ID_DEFAULT, {150, 50}))
5934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5935 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5936 mWindow->consumeDragEvent(true, 150, 50);
5937 mSecondWindow->consumeDragEvent(false, 50, 50);
5938
5939 // Move back to original window.
5940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5941 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5942 ADISPLAY_ID_DEFAULT, {50, 50}))
5943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5944 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5945 mWindow->consumeDragEvent(false, 50, 50);
5946 mSecondWindow->consumeDragEvent(true, -50, 50);
5947
5948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5949 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5951 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5952 mWindow->assertNoEvents();
5953 mSecondWindow->assertNoEvents();
5954}
5955
arthurhungf452d0b2021-01-06 00:19:52 +08005956TEST_F(InputDispatcherDragTests, DragAndDrop) {
5957 performDrag();
5958
5959 // Move on window.
5960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5961 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5962 ADISPLAY_ID_DEFAULT, {50, 50}))
5963 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5964 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5965 mWindow->consumeDragEvent(false, 50, 50);
5966 mSecondWindow->assertNoEvents();
5967
5968 // Move to another window.
5969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5970 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5971 ADISPLAY_ID_DEFAULT, {150, 50}))
5972 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5973 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5974 mWindow->consumeDragEvent(true, 150, 50);
5975 mSecondWindow->consumeDragEvent(false, 50, 50);
5976
5977 // drop to another window.
5978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5979 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5980 {150, 50}))
5981 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5982 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5983 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5984 mWindow->assertNoEvents();
5985 mSecondWindow->assertNoEvents();
5986}
5987
arthurhung6d4bed92021-03-17 11:59:33 +08005988TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5989 performStylusDrag();
5990
5991 // Move on window and keep button pressed.
5992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5993 injectMotionEvent(mDispatcher,
5994 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5995 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5996 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5997 .x(50)
5998 .y(50))
5999 .build()))
6000 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6001 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6002 mWindow->consumeDragEvent(false, 50, 50);
6003 mSecondWindow->assertNoEvents();
6004
6005 // Move to another window and release button, expect to drop item.
6006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6007 injectMotionEvent(mDispatcher,
6008 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6009 .buttonState(0)
6010 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6011 .x(150)
6012 .y(50))
6013 .build()))
6014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6015 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6016 mWindow->assertNoEvents();
6017 mSecondWindow->assertNoEvents();
6018 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6019
6020 // nothing to the window.
6021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6022 injectMotionEvent(mDispatcher,
6023 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6024 .buttonState(0)
6025 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6026 .x(150)
6027 .y(50))
6028 .build()))
6029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6030 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6031 mWindow->assertNoEvents();
6032 mSecondWindow->assertNoEvents();
6033}
6034
Arthur Hung6d0571e2021-04-09 20:18:16 +08006035TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6036 performDrag();
6037
6038 // Set second window invisible.
6039 mSecondWindow->setVisible(false);
6040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6041
6042 // Move on window.
6043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6044 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6045 ADISPLAY_ID_DEFAULT, {50, 50}))
6046 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6047 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6048 mWindow->consumeDragEvent(false, 50, 50);
6049 mSecondWindow->assertNoEvents();
6050
6051 // Move to another window.
6052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6053 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6054 ADISPLAY_ID_DEFAULT, {150, 50}))
6055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6056 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6057 mWindow->consumeDragEvent(true, 150, 50);
6058 mSecondWindow->assertNoEvents();
6059
6060 // drop to another window.
6061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6062 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6063 {150, 50}))
6064 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6065 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6066 mFakePolicy->assertDropTargetEquals(nullptr);
6067 mWindow->assertNoEvents();
6068 mSecondWindow->assertNoEvents();
6069}
6070
Vishnu Nair062a8672021-09-03 16:07:44 -07006071class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6072
6073TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6074 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6075 sp<FakeWindowHandle> window =
6076 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6077 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6079 window->setFocusable(true);
6080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6081 setFocusedWindow(window);
6082 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6083
6084 // With the flag set, window should not get any input
6085 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6086 mDispatcher->notifyKey(&keyArgs);
6087 window->assertNoEvents();
6088
6089 NotifyMotionArgs motionArgs =
6090 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6091 ADISPLAY_ID_DEFAULT);
6092 mDispatcher->notifyMotion(&motionArgs);
6093 window->assertNoEvents();
6094
6095 // With the flag cleared, the window should get input
6096 window->setInputFeatures({});
6097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6098
6099 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6100 mDispatcher->notifyKey(&keyArgs);
6101 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6102
6103 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6104 ADISPLAY_ID_DEFAULT);
6105 mDispatcher->notifyMotion(&motionArgs);
6106 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6107 window->assertNoEvents();
6108}
6109
6110TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6111 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6112 std::make_shared<FakeApplicationHandle>();
6113 sp<FakeWindowHandle> obscuringWindow =
6114 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6115 ADISPLAY_ID_DEFAULT);
6116 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6117 obscuringWindow->setOwnerInfo(111, 111);
6118 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6119 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6120 sp<FakeWindowHandle> window =
6121 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6122 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6123 window->setOwnerInfo(222, 222);
6124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6125 window->setFocusable(true);
6126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6127 setFocusedWindow(window);
6128 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6129
6130 // With the flag set, window should not get any input
6131 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6132 mDispatcher->notifyKey(&keyArgs);
6133 window->assertNoEvents();
6134
6135 NotifyMotionArgs motionArgs =
6136 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6137 ADISPLAY_ID_DEFAULT);
6138 mDispatcher->notifyMotion(&motionArgs);
6139 window->assertNoEvents();
6140
6141 // With the flag cleared, the window should get input
6142 window->setInputFeatures({});
6143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6144
6145 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6146 mDispatcher->notifyKey(&keyArgs);
6147 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6148
6149 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6150 ADISPLAY_ID_DEFAULT);
6151 mDispatcher->notifyMotion(&motionArgs);
6152 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6153 window->assertNoEvents();
6154}
6155
6156TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6157 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6158 std::make_shared<FakeApplicationHandle>();
6159 sp<FakeWindowHandle> obscuringWindow =
6160 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6161 ADISPLAY_ID_DEFAULT);
6162 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6163 obscuringWindow->setOwnerInfo(111, 111);
6164 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6165 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6166 sp<FakeWindowHandle> window =
6167 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6168 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6169 window->setOwnerInfo(222, 222);
6170 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6171 window->setFocusable(true);
6172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6173 setFocusedWindow(window);
6174 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6175
6176 // With the flag set, window should not get any input
6177 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6178 mDispatcher->notifyKey(&keyArgs);
6179 window->assertNoEvents();
6180
6181 NotifyMotionArgs motionArgs =
6182 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6183 ADISPLAY_ID_DEFAULT);
6184 mDispatcher->notifyMotion(&motionArgs);
6185 window->assertNoEvents();
6186
6187 // When the window is no longer obscured because it went on top, it should get input
6188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6189
6190 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6191 mDispatcher->notifyKey(&keyArgs);
6192 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6193
6194 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6195 ADISPLAY_ID_DEFAULT);
6196 mDispatcher->notifyMotion(&motionArgs);
6197 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6198 window->assertNoEvents();
6199}
6200
Antonio Kantekf16f2832021-09-28 04:39:20 +00006201class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6202protected:
6203 std::shared_ptr<FakeApplicationHandle> mApp;
6204 sp<FakeWindowHandle> mWindow;
6205 sp<FakeWindowHandle> mSecondWindow;
6206
6207 void SetUp() override {
6208 InputDispatcherTest::SetUp();
6209
6210 mApp = std::make_shared<FakeApplicationHandle>();
6211 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6212 mWindow->setFocusable(true);
6213 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6214 mSecondWindow->setFocusable(true);
6215
6216 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6218
6219 setFocusedWindow(mWindow);
6220 mWindow->consumeFocusEvent(true);
6221 }
6222
6223 void changeAndVerifyTouchMode(bool inTouchMode) {
6224 mDispatcher->setInTouchMode(inTouchMode);
6225 mWindow->consumeTouchModeEvent(inTouchMode);
6226 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6227 }
6228};
6229
6230TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6231 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6232}
6233
6234TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6235 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6236 mWindow->assertNoEvents();
6237 mSecondWindow->assertNoEvents();
6238}
6239
Garfield Tane84e6f92019-08-29 17:28:41 -07006240} // namespace android::inputdispatcher