blob: 3c6f1ff7c6cc1e8eec2ec397301cff04bae9b217 [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
Arthur Hungdfd528e2021-12-08 13:23:04 +00003799TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3800 FakeMonitorReceiver monitorInPrimary =
3801 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3802 FakeMonitorReceiver monitorInSecondary =
3803 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3804
3805 // Test touch down on primary display.
3806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3807 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3808 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3809 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3810 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3811
3812 // Test touch down on second display.
3813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3814 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3816 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3817 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3818
3819 // Trigger cancel touch.
3820 mDispatcher->cancelCurrentTouch();
3821 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3822 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3823 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3824 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3825
3826 // Test inject a move motion event, no window/monitor should receive the event.
3827 ASSERT_EQ(InputEventInjectionResult::FAILED,
3828 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3829 ADISPLAY_ID_DEFAULT, {110, 200}))
3830 << "Inject motion event should return InputEventInjectionResult::FAILED";
3831 windowInPrimary->assertNoEvents();
3832 monitorInPrimary.assertNoEvents();
3833
3834 ASSERT_EQ(InputEventInjectionResult::FAILED,
3835 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3836 SECOND_DISPLAY_ID, {110, 200}))
3837 << "Inject motion event should return InputEventInjectionResult::FAILED";
3838 windowInSecondary->assertNoEvents();
3839 monitorInSecondary.assertNoEvents();
3840}
3841
Jackal Guof9696682018-10-05 12:23:23 +08003842class InputFilterTest : public InputDispatcherTest {
3843protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003844 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3845 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003846 NotifyMotionArgs motionArgs;
3847
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003848 motionArgs =
3849 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003850 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003851 motionArgs =
3852 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003853 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003854 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003855 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003856 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3857 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003858 } else {
3859 mFakePolicy->assertFilterInputEventWasNotCalled();
3860 }
3861 }
3862
3863 void testNotifyKey(bool expectToBeFiltered) {
3864 NotifyKeyArgs keyArgs;
3865
3866 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3867 mDispatcher->notifyKey(&keyArgs);
3868 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3869 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003870 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003871
3872 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003873 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003874 } else {
3875 mFakePolicy->assertFilterInputEventWasNotCalled();
3876 }
3877 }
3878};
3879
3880// Test InputFilter for MotionEvent
3881TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3882 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3883 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3884 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3885
3886 // Enable InputFilter
3887 mDispatcher->setInputFilterEnabled(true);
3888 // Test touch on both primary and second display, and check if both events are filtered.
3889 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3890 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3891
3892 // Disable InputFilter
3893 mDispatcher->setInputFilterEnabled(false);
3894 // Test touch on both primary and second display, and check if both events aren't filtered.
3895 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3896 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3897}
3898
3899// Test InputFilter for KeyEvent
3900TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3901 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3902 testNotifyKey(/*expectToBeFiltered*/ false);
3903
3904 // Enable InputFilter
3905 mDispatcher->setInputFilterEnabled(true);
3906 // Send a key event, and check if it is filtered.
3907 testNotifyKey(/*expectToBeFiltered*/ true);
3908
3909 // Disable InputFilter
3910 mDispatcher->setInputFilterEnabled(false);
3911 // Send a key event, and check if it isn't filtered.
3912 testNotifyKey(/*expectToBeFiltered*/ false);
3913}
3914
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003915// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3916// logical display coordinate space.
3917TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3918 ui::Transform firstDisplayTransform;
3919 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3920 ui::Transform secondDisplayTransform;
3921 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3922
3923 std::vector<gui::DisplayInfo> displayInfos(2);
3924 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3925 displayInfos[0].transform = firstDisplayTransform;
3926 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3927 displayInfos[1].transform = secondDisplayTransform;
3928
3929 mDispatcher->onWindowInfosChanged({}, displayInfos);
3930
3931 // Enable InputFilter
3932 mDispatcher->setInputFilterEnabled(true);
3933
3934 // Ensure the correct transforms are used for the displays.
3935 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3936 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3937}
3938
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003939class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3940protected:
3941 virtual void SetUp() override {
3942 InputDispatcherTest::SetUp();
3943
3944 /**
3945 * We don't need to enable input filter to test the injected event policy, but we enabled it
3946 * here to make the tests more realistic, since this policy only matters when inputfilter is
3947 * on.
3948 */
3949 mDispatcher->setInputFilterEnabled(true);
3950
3951 std::shared_ptr<InputApplicationHandle> application =
3952 std::make_shared<FakeApplicationHandle>();
3953 mWindow =
3954 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3955
3956 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3957 mWindow->setFocusable(true);
3958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3959 setFocusedWindow(mWindow);
3960 mWindow->consumeFocusEvent(true);
3961 }
3962
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003963 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3964 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003965 KeyEvent event;
3966
3967 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3968 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3969 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3970 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3971 const int32_t additionalPolicyFlags =
3972 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3974 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3975 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3976 policyFlags | additionalPolicyFlags));
3977
3978 InputEvent* received = mWindow->consume();
3979 ASSERT_NE(nullptr, received);
3980 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003981 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3982 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3983 ASSERT_EQ(flags, keyEvent.getFlags());
3984 }
3985
3986 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3987 int32_t flags) {
3988 MotionEvent event;
3989 PointerProperties pointerProperties[1];
3990 PointerCoords pointerCoords[1];
3991 pointerProperties[0].clear();
3992 pointerProperties[0].id = 0;
3993 pointerCoords[0].clear();
3994 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3995 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3996
3997 ui::Transform identityTransform;
3998 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3999 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4000 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4001 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4002 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004003 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004004 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004005 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4006
4007 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4009 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4010 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4011 policyFlags | additionalPolicyFlags));
4012
4013 InputEvent* received = mWindow->consume();
4014 ASSERT_NE(nullptr, received);
4015 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4016 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4017 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4018 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004019 }
4020
4021private:
4022 sp<FakeWindowHandle> mWindow;
4023};
4024
4025TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004026 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4027 // filter. Without it, the event will no different from a regularly injected event, and the
4028 // injected device id will be overwritten.
4029 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4030 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004031}
4032
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004033TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004034 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004035 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4036 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4037}
4038
4039TEST_F(InputFilterInjectionPolicyTest,
4040 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4041 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4042 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4043 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004044}
4045
4046TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4047 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004048 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004049}
4050
chaviwfd6d3512019-03-25 13:23:49 -07004051class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004052 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004053 InputDispatcherTest::SetUp();
4054
Chris Yea209fde2020-07-22 13:54:51 -07004055 std::shared_ptr<FakeApplicationHandle> application =
4056 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004057 mUnfocusedWindow =
4058 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004059 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4060 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4061 // window.
chaviw3277faf2021-05-19 16:45:23 -05004062 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004063
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004064 mFocusedWindow =
4065 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4066 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004067 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004068
4069 // Set focused application.
4070 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004071 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004072
4073 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004075 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004076 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004077 }
4078
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004079 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004080 InputDispatcherTest::TearDown();
4081
4082 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004083 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004084 }
4085
4086protected:
4087 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004088 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004089 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004090};
4091
4092// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4093// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4094// the onPointerDownOutsideFocus callback.
4095TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004097 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4098 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004099 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004100 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004101
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004102 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004103 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4104}
4105
4106// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4107// DOWN on the window that doesn't have focus. Ensure no window received the
4108// onPointerDownOutsideFocus callback.
4109TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004110 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004111 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004113 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004114
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004115 ASSERT_TRUE(mDispatcher->waitForIdle());
4116 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004117}
4118
4119// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4120// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4121TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4123 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004125 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004126
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004127 ASSERT_TRUE(mDispatcher->waitForIdle());
4128 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004129}
4130
4131// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4132// DOWN on the window that already has focus. Ensure no window received the
4133// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004134TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004136 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004137 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004138 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004139 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004140
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004141 ASSERT_TRUE(mDispatcher->waitForIdle());
4142 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004143}
4144
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004145// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4146// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4147TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4148 const MotionEvent event =
4149 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4150 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4151 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4152 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4153 .build();
4154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4155 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4156 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4157
4158 ASSERT_TRUE(mDispatcher->waitForIdle());
4159 mFakePolicy->assertOnPointerDownWasNotCalled();
4160 // Ensure that the unfocused window did not receive any FOCUS events.
4161 mUnfocusedWindow->assertNoEvents();
4162}
4163
chaviwaf87b3e2019-10-01 16:59:28 -07004164// These tests ensures we can send touch events to a single client when there are multiple input
4165// windows that point to the same client token.
4166class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4167 virtual void SetUp() override {
4168 InputDispatcherTest::SetUp();
4169
Chris Yea209fde2020-07-22 13:54:51 -07004170 std::shared_ptr<FakeApplicationHandle> application =
4171 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004172 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4173 ADISPLAY_ID_DEFAULT);
4174 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4175 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004176 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004177 mWindow1->setFrame(Rect(0, 0, 100, 100));
4178
4179 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4180 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004181 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004182 mWindow2->setFrame(Rect(100, 100, 200, 200));
4183
Arthur Hung72d8dc32020-03-28 00:48:39 +00004184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004185 }
4186
4187protected:
4188 sp<FakeWindowHandle> mWindow1;
4189 sp<FakeWindowHandle> mWindow2;
4190
4191 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004192 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004193 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4194 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004195 }
4196
4197 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4198 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004199 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004200 InputEvent* event = window->consume();
4201
4202 ASSERT_NE(nullptr, event) << name.c_str()
4203 << ": consumer should have returned non-NULL event.";
4204
4205 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4206 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4207 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4208
4209 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004210 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004211
4212 for (size_t i = 0; i < points.size(); i++) {
4213 float expectedX = points[i].x;
4214 float expectedY = points[i].y;
4215
4216 EXPECT_EQ(expectedX, motionEvent.getX(i))
4217 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4218 << ", got " << motionEvent.getX(i);
4219 EXPECT_EQ(expectedY, motionEvent.getY(i))
4220 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4221 << ", got " << motionEvent.getY(i);
4222 }
4223 }
chaviw9eaa22c2020-07-01 16:21:27 -07004224
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004225 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004226 std::vector<PointF> expectedPoints) {
4227 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4228 ADISPLAY_ID_DEFAULT, touchedPoints);
4229 mDispatcher->notifyMotion(&motionArgs);
4230
4231 // Always consume from window1 since it's the window that has the InputReceiver
4232 consumeMotionEvent(mWindow1, action, expectedPoints);
4233 }
chaviwaf87b3e2019-10-01 16:59:28 -07004234};
4235
4236TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4237 // Touch Window 1
4238 PointF touchedPoint = {10, 10};
4239 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004240 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004241
4242 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004243 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004244
4245 // Touch Window 2
4246 touchedPoint = {150, 150};
4247 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004248 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004249}
4250
chaviw9eaa22c2020-07-01 16:21:27 -07004251TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4252 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004253 mWindow2->setWindowScale(0.5f, 0.5f);
4254
4255 // Touch Window 1
4256 PointF touchedPoint = {10, 10};
4257 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004259 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004260 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004261
4262 // Touch Window 2
4263 touchedPoint = {150, 150};
4264 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004265 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4266 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004267
chaviw9eaa22c2020-07-01 16:21:27 -07004268 // Update the transform so rotation is set
4269 mWindow2->setWindowTransform(0, -1, 1, 0);
4270 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4271 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004272}
4273
chaviw9eaa22c2020-07-01 16:21:27 -07004274TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004275 mWindow2->setWindowScale(0.5f, 0.5f);
4276
4277 // Touch Window 1
4278 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4279 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004281
4282 // Touch Window 2
4283 int32_t actionPointerDown =
4284 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004285 touchedPoints.push_back(PointF{150, 150});
4286 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4287 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004288
chaviw9eaa22c2020-07-01 16:21:27 -07004289 // Release Window 2
4290 int32_t actionPointerUp =
4291 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4292 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4293 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004294
chaviw9eaa22c2020-07-01 16:21:27 -07004295 // Update the transform so rotation is set for Window 2
4296 mWindow2->setWindowTransform(0, -1, 1, 0);
4297 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4298 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004299}
4300
chaviw9eaa22c2020-07-01 16:21:27 -07004301TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004302 mWindow2->setWindowScale(0.5f, 0.5f);
4303
4304 // Touch Window 1
4305 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4306 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004307 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004308
4309 // Touch Window 2
4310 int32_t actionPointerDown =
4311 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004312 touchedPoints.push_back(PointF{150, 150});
4313 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004314
chaviw9eaa22c2020-07-01 16:21:27 -07004315 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004316
4317 // Move both windows
4318 touchedPoints = {{20, 20}, {175, 175}};
4319 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4320 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4321
chaviw9eaa22c2020-07-01 16:21:27 -07004322 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004323
chaviw9eaa22c2020-07-01 16:21:27 -07004324 // Release Window 2
4325 int32_t actionPointerUp =
4326 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4327 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4328 expectedPoints.pop_back();
4329
4330 // Touch Window 2
4331 mWindow2->setWindowTransform(0, -1, 1, 0);
4332 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4333 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4334
4335 // Move both windows
4336 touchedPoints = {{20, 20}, {175, 175}};
4337 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4338 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4339
4340 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004341}
4342
4343TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4344 mWindow1->setWindowScale(0.5f, 0.5f);
4345
4346 // Touch Window 1
4347 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4348 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004349 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004350
4351 // Touch Window 2
4352 int32_t actionPointerDown =
4353 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004354 touchedPoints.push_back(PointF{150, 150});
4355 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004356
chaviw9eaa22c2020-07-01 16:21:27 -07004357 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004358
4359 // Move both windows
4360 touchedPoints = {{20, 20}, {175, 175}};
4361 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4362 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4363
chaviw9eaa22c2020-07-01 16:21:27 -07004364 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004365}
4366
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004367class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4368 virtual void SetUp() override {
4369 InputDispatcherTest::SetUp();
4370
Chris Yea209fde2020-07-22 13:54:51 -07004371 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004372 mApplication->setDispatchingTimeout(20ms);
4373 mWindow =
4374 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4375 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004376 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004377 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004378 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4379 // window.
chaviw3277faf2021-05-19 16:45:23 -05004380 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004381
4382 // Set focused application.
4383 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4384
4385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004386 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004387 mWindow->consumeFocusEvent(true);
4388 }
4389
4390 virtual void TearDown() override {
4391 InputDispatcherTest::TearDown();
4392 mWindow.clear();
4393 }
4394
4395protected:
Chris Yea209fde2020-07-22 13:54:51 -07004396 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397 sp<FakeWindowHandle> mWindow;
4398 static constexpr PointF WINDOW_LOCATION = {20, 20};
4399
4400 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004402 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4403 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4406 WINDOW_LOCATION));
4407 }
4408};
4409
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004410// Send a tap and respond, which should not cause an ANR.
4411TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4412 tapOnWindow();
4413 mWindow->consumeMotionDown();
4414 mWindow->consumeMotionUp();
4415 ASSERT_TRUE(mDispatcher->waitForIdle());
4416 mFakePolicy->assertNotifyAnrWasNotCalled();
4417}
4418
4419// Send a regular key and respond, which should not cause an ANR.
4420TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004422 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4423 ASSERT_TRUE(mDispatcher->waitForIdle());
4424 mFakePolicy->assertNotifyAnrWasNotCalled();
4425}
4426
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004427TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4428 mWindow->setFocusable(false);
4429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4430 mWindow->consumeFocusEvent(false);
4431
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004433 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004434 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4435 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004437 // Key will not go to window because we have no focused window.
4438 // The 'no focused window' ANR timer should start instead.
4439
4440 // Now, the focused application goes away.
4441 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4442 // The key should get dropped and there should be no ANR.
4443
4444 ASSERT_TRUE(mDispatcher->waitForIdle());
4445 mFakePolicy->assertNotifyAnrWasNotCalled();
4446}
4447
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004448// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004449// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4450// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004451TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004453 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4454 WINDOW_LOCATION));
4455
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004456 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4457 ASSERT_TRUE(sequenceNum);
4458 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004459 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004461 mWindow->finishEvent(*sequenceNum);
4462 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4463 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004464 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004465 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004466}
4467
4468// Send a key to the app and have the app not respond right away.
4469TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4470 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004472 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4473 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004474 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004475 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004476 ASSERT_TRUE(mDispatcher->waitForIdle());
4477}
4478
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479// We have a focused application, but no focused window
4480TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004481 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4483 mWindow->consumeFocusEvent(false);
4484
4485 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004487 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4488 WINDOW_LOCATION));
4489 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4490 mDispatcher->waitForIdle();
4491 mFakePolicy->assertNotifyAnrWasNotCalled();
4492
4493 // Once a focused event arrives, we get an ANR for this application
4494 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4495 // injection times out (instead of failing).
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,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004498 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004501 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004502 ASSERT_TRUE(mDispatcher->waitForIdle());
4503}
4504
4505// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004506// Make sure that we don't notify policy twice about the same ANR.
4507TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004508 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4510 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004511
4512 // Once a focused event arrives, we get an ANR for this application
4513 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4514 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004515 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004516 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004517 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004518 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004519 const std::chrono::duration appTimeout =
4520 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004521 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004522
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004523 std::this_thread::sleep_for(appTimeout);
4524 // ANR should not be raised again. It is up to policy to do that if it desires.
4525 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004526
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004527 // If we now get a focused window, the ANR should stop, but the policy handles that via
4528 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529 ASSERT_TRUE(mDispatcher->waitForIdle());
4530}
4531
4532// We have a focused application, but no focused window
4533TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004534 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4536 mWindow->consumeFocusEvent(false);
4537
4538 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004539 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004541 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4542 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004543
4544 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004545 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546
4547 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549 ASSERT_TRUE(mDispatcher->waitForIdle());
4550 mWindow->assertNoEvents();
4551}
4552
4553/**
4554 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4555 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4556 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4557 * the ANR mechanism should still work.
4558 *
4559 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4560 * DOWN event, while not responding on the second one.
4561 */
4562TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4563 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4564 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4565 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4566 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4567 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004568 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569
4570 // Now send ACTION_UP, with identical timestamp
4571 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4572 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4573 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4574 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004576
4577 // We have now sent down and up. Let's consume first event and then ANR on the second.
4578 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4579 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004580 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581}
4582
4583// If an app is not responding to a key event, gesture monitors should continue to receive
4584// new motion events
4585TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4586 FakeMonitorReceiver monitor =
4587 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4588 true /*isGestureMonitor*/);
4589
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4591 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594
4595 // Stuck on the ACTION_UP
4596 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004597 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004598
4599 // New tap will go to the gesture monitor, but not to the window
4600 tapOnWindow();
4601 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4602 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4603
4604 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4605 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004606 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004607 mWindow->assertNoEvents();
4608 monitor.assertNoEvents();
4609}
4610
4611// If an app is not responding to a motion event, gesture monitors should continue to receive
4612// new motion events
4613TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4614 FakeMonitorReceiver monitor =
4615 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4616 true /*isGestureMonitor*/);
4617
4618 tapOnWindow();
4619 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4620 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4621
4622 mWindow->consumeMotionDown();
4623 // Stuck on the ACTION_UP
4624 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004625 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626
4627 // New tap will go to the gesture monitor, but not to the window
4628 tapOnWindow();
4629 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4630 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4631
4632 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4633 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004634 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635 mWindow->assertNoEvents();
4636 monitor.assertNoEvents();
4637}
4638
4639// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4640// process events, you don't get an anr. When the window later becomes unresponsive again, you
4641// get an ANR again.
4642// 1. tap -> block on ACTION_UP -> receive ANR
4643// 2. consume all pending events (= queue becomes healthy again)
4644// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4645TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4646 tapOnWindow();
4647
4648 mWindow->consumeMotionDown();
4649 // Block on ACTION_UP
4650 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004651 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4653 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004654 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655 mWindow->assertNoEvents();
4656
4657 tapOnWindow();
4658 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004659 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660 mWindow->consumeMotionUp();
4661
4662 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004663 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004664 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004665 mWindow->assertNoEvents();
4666}
4667
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004668// If a connection remains unresponsive for a while, make sure policy is only notified once about
4669// it.
4670TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4673 WINDOW_LOCATION));
4674
4675 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004676 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004678 // 'notifyConnectionUnresponsive' should only be called once per connection
4679 mFakePolicy->assertNotifyAnrWasNotCalled();
4680 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681 mWindow->consumeMotionDown();
4682 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4683 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4684 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004685 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004686 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004687 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688}
4689
4690/**
4691 * If a window is processing a motion event, and then a key event comes in, the key event should
4692 * not to to the focused window until the motion is processed.
4693 *
4694 * Warning!!!
4695 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4696 * and the injection timeout that we specify when injecting the key.
4697 * We must have the injection timeout (10ms) be smaller than
4698 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4699 *
4700 * If that value changes, this test should also change.
4701 */
4702TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4703 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4705
4706 tapOnWindow();
4707 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4708 ASSERT_TRUE(downSequenceNum);
4709 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4710 ASSERT_TRUE(upSequenceNum);
4711 // Don't finish the events yet, and send a key
4712 // Injection will "succeed" because we will eventually give up and send the key to the focused
4713 // window even if motions are still being processed. But because the injection timeout is short,
4714 // we will receive INJECTION_TIMED_OUT as the result.
4715
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004716 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004717 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004718 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4719 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004720 // Key will not be sent to the window, yet, because the window is still processing events
4721 // and the key remains pending, waiting for the touch events to be processed
4722 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4723 ASSERT_FALSE(keySequenceNum);
4724
4725 std::this_thread::sleep_for(500ms);
4726 // if we wait long enough though, dispatcher will give up, and still send the key
4727 // to the focused window, even though we have not yet finished the motion event
4728 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4729 mWindow->finishEvent(*downSequenceNum);
4730 mWindow->finishEvent(*upSequenceNum);
4731}
4732
4733/**
4734 * If a window is processing a motion event, and then a key event comes in, the key event should
4735 * not go to the focused window until the motion is processed.
4736 * If then a new motion comes in, then the pending key event should be going to the currently
4737 * focused window right away.
4738 */
4739TEST_F(InputDispatcherSingleWindowAnr,
4740 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4741 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4743
4744 tapOnWindow();
4745 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4746 ASSERT_TRUE(downSequenceNum);
4747 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4748 ASSERT_TRUE(upSequenceNum);
4749 // Don't finish the events yet, and send a key
4750 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 // At this point, key is still pending, and should not be sent to the application yet.
4755 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4756 ASSERT_FALSE(keySequenceNum);
4757
4758 // Now tap down again. It should cause the pending key to go to the focused window right away.
4759 tapOnWindow();
4760 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4761 // the other events yet. We can finish events in any order.
4762 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4763 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4764 mWindow->consumeMotionDown();
4765 mWindow->consumeMotionUp();
4766 mWindow->assertNoEvents();
4767}
4768
4769class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4770 virtual void SetUp() override {
4771 InputDispatcherTest::SetUp();
4772
Chris Yea209fde2020-07-22 13:54:51 -07004773 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 mApplication->setDispatchingTimeout(10ms);
4775 mUnfocusedWindow =
4776 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4777 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4778 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4779 // window.
4780 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004781 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4782 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4783 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784
4785 mFocusedWindow =
4786 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004787 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004789 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790
4791 // Set focused application.
4792 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004793 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794
4795 // Expect one focus window exist in display.
4796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004797 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 mFocusedWindow->consumeFocusEvent(true);
4799 }
4800
4801 virtual void TearDown() override {
4802 InputDispatcherTest::TearDown();
4803
4804 mUnfocusedWindow.clear();
4805 mFocusedWindow.clear();
4806 }
4807
4808protected:
Chris Yea209fde2020-07-22 13:54:51 -07004809 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 sp<FakeWindowHandle> mUnfocusedWindow;
4811 sp<FakeWindowHandle> mFocusedWindow;
4812 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4813 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4814 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4815
4816 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4817
4818 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4819
4820private:
4821 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4824 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004825 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4827 location));
4828 }
4829};
4830
4831// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4832// should be ANR'd first.
4833TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4836 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 mFocusedWindow->consumeMotionDown();
4839 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4840 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4841 // We consumed all events, so no ANR
4842 ASSERT_TRUE(mDispatcher->waitForIdle());
4843 mFakePolicy->assertNotifyAnrWasNotCalled();
4844
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004845 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4847 FOCUSED_WINDOW_LOCATION));
4848 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4849 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850
4851 const std::chrono::duration timeout =
4852 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004853 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004854 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4855 // sequence to make it consistent
4856 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004858 mFocusedWindow->consumeMotionDown();
4859 // This cancel is generated because the connection was unresponsive
4860 mFocusedWindow->consumeMotionCancel();
4861 mFocusedWindow->assertNoEvents();
4862 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004864 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004865 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866}
4867
4868// If we have 2 windows with identical timeouts that are both unresponsive,
4869// it doesn't matter which order they should have ANR.
4870// But we should receive ANR for both.
4871TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4872 // Set the timeout for unfocused window to match the focused window
4873 mUnfocusedWindow->setDispatchingTimeout(10ms);
4874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4875
4876 tapOnFocusedWindow();
4877 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004878 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4879 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004880
4881 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004882 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4883 mFocusedWindow->getToken() == anrConnectionToken2);
4884 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4885 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886
4887 ASSERT_TRUE(mDispatcher->waitForIdle());
4888 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004889
4890 mFocusedWindow->consumeMotionDown();
4891 mFocusedWindow->consumeMotionUp();
4892 mUnfocusedWindow->consumeMotionOutside();
4893
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004894 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4895 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004896
4897 // Both applications should be marked as responsive, in any order
4898 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4899 mFocusedWindow->getToken() == responsiveToken2);
4900 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4901 mUnfocusedWindow->getToken() == responsiveToken2);
4902 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903}
4904
4905// If a window is already not responding, the second tap on the same window should be ignored.
4906// We should also log an error to account for the dropped event (not tested here).
4907// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4908TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4909 tapOnFocusedWindow();
4910 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4911 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4912 // Receive the events, but don't respond
4913 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4914 ASSERT_TRUE(downEventSequenceNum);
4915 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4916 ASSERT_TRUE(upEventSequenceNum);
4917 const std::chrono::duration timeout =
4918 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004919 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 // Tap once again
4922 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004923 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4925 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004926 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004927 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4928 FOCUSED_WINDOW_LOCATION));
4929 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4930 // valid touch target
4931 mUnfocusedWindow->assertNoEvents();
4932
4933 // Consume the first tap
4934 mFocusedWindow->finishEvent(*downEventSequenceNum);
4935 mFocusedWindow->finishEvent(*upEventSequenceNum);
4936 ASSERT_TRUE(mDispatcher->waitForIdle());
4937 // The second tap did not go to the focused window
4938 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004939 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004940 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 mFakePolicy->assertNotifyAnrWasNotCalled();
4942}
4943
4944// If you tap outside of all windows, there will not be ANR
4945TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004946 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4948 LOCATION_OUTSIDE_ALL_WINDOWS));
4949 ASSERT_TRUE(mDispatcher->waitForIdle());
4950 mFakePolicy->assertNotifyAnrWasNotCalled();
4951}
4952
4953// Since the focused window is paused, tapping on it should not produce any events
4954TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4955 mFocusedWindow->setPaused(true);
4956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4957
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004958 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4960 FOCUSED_WINDOW_LOCATION));
4961
4962 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4963 ASSERT_TRUE(mDispatcher->waitForIdle());
4964 // Should not ANR because the window is paused, and touches shouldn't go to it
4965 mFakePolicy->assertNotifyAnrWasNotCalled();
4966
4967 mFocusedWindow->assertNoEvents();
4968 mUnfocusedWindow->assertNoEvents();
4969}
4970
4971/**
4972 * If a window is processing a motion event, and then a key event comes in, the key event should
4973 * not to to the focused window until the motion is processed.
4974 * If a different window becomes focused at this time, the key should go to that window instead.
4975 *
4976 * Warning!!!
4977 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4978 * and the injection timeout that we specify when injecting the key.
4979 * We must have the injection timeout (10ms) be smaller than
4980 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4981 *
4982 * If that value changes, this test should also change.
4983 */
4984TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4985 // Set a long ANR timeout to prevent it from triggering
4986 mFocusedWindow->setDispatchingTimeout(2s);
4987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4988
4989 tapOnUnfocusedWindow();
4990 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4991 ASSERT_TRUE(downSequenceNum);
4992 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4993 ASSERT_TRUE(upSequenceNum);
4994 // Don't finish the events yet, and send a key
4995 // Injection will succeed because we will eventually give up and send the key to the focused
4996 // window even if motions are still being processed.
4997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004998 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005000 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002 // Key will not be sent to the window, yet, because the window is still processing events
5003 // and the key remains pending, waiting for the touch events to be processed
5004 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5005 ASSERT_FALSE(keySequenceNum);
5006
5007 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005008 mFocusedWindow->setFocusable(false);
5009 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005011 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012
5013 // Focus events should precede the key events
5014 mUnfocusedWindow->consumeFocusEvent(true);
5015 mFocusedWindow->consumeFocusEvent(false);
5016
5017 // Finish the tap events, which should unblock dispatcher
5018 mUnfocusedWindow->finishEvent(*downSequenceNum);
5019 mUnfocusedWindow->finishEvent(*upSequenceNum);
5020
5021 // Now that all queues are cleared and no backlog in the connections, the key event
5022 // can finally go to the newly focused "mUnfocusedWindow".
5023 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5024 mFocusedWindow->assertNoEvents();
5025 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005026 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005027}
5028
5029// When the touch stream is split across 2 windows, and one of them does not respond,
5030// then ANR should be raised and the touch should be canceled for the unresponsive window.
5031// The other window should not be affected by that.
5032TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5033 // Touch Window 1
5034 NotifyMotionArgs motionArgs =
5035 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5036 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5037 mDispatcher->notifyMotion(&motionArgs);
5038 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5039 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5040
5041 // Touch Window 2
5042 int32_t actionPointerDown =
5043 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5044
5045 motionArgs =
5046 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5047 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5048 mDispatcher->notifyMotion(&motionArgs);
5049
5050 const std::chrono::duration timeout =
5051 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005052 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005053
5054 mUnfocusedWindow->consumeMotionDown();
5055 mFocusedWindow->consumeMotionDown();
5056 // Focused window may or may not receive ACTION_MOVE
5057 // But it should definitely receive ACTION_CANCEL due to the ANR
5058 InputEvent* event;
5059 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5060 ASSERT_TRUE(moveOrCancelSequenceNum);
5061 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5062 ASSERT_NE(nullptr, event);
5063 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5064 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5065 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5066 mFocusedWindow->consumeMotionCancel();
5067 } else {
5068 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5069 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005070 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005071 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005072
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005073 mUnfocusedWindow->assertNoEvents();
5074 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005075 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005076}
5077
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005078/**
5079 * If we have no focused window, and a key comes in, we start the ANR timer.
5080 * The focused application should add a focused window before the timer runs out to prevent ANR.
5081 *
5082 * If the user touches another application during this time, the key should be dropped.
5083 * Next, if a new focused window comes in, without toggling the focused application,
5084 * then no ANR should occur.
5085 *
5086 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5087 * but in some cases the policy may not update the focused application.
5088 */
5089TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5090 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5091 std::make_shared<FakeApplicationHandle>();
5092 focusedApplication->setDispatchingTimeout(60ms);
5093 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5094 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5095 mFocusedWindow->setFocusable(false);
5096
5097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5098 mFocusedWindow->consumeFocusEvent(false);
5099
5100 // Send a key. The ANR timer should start because there is no focused window.
5101 // 'focusedApplication' will get blamed if this timer completes.
5102 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005104 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005105 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5106 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005108
5109 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5110 // then the injected touches won't cause the focused event to get dropped.
5111 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5112 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5113 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5114 // For this test, it means that the key would get delivered to the window once it becomes
5115 // focused.
5116 std::this_thread::sleep_for(10ms);
5117
5118 // Touch unfocused window. This should force the pending key to get dropped.
5119 NotifyMotionArgs motionArgs =
5120 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5121 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5122 mDispatcher->notifyMotion(&motionArgs);
5123
5124 // We do not consume the motion right away, because that would require dispatcher to first
5125 // process (== drop) the key event, and by that time, ANR will be raised.
5126 // Set the focused window first.
5127 mFocusedWindow->setFocusable(true);
5128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5129 setFocusedWindow(mFocusedWindow);
5130 mFocusedWindow->consumeFocusEvent(true);
5131 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5132 // to another application. This could be a bug / behaviour in the policy.
5133
5134 mUnfocusedWindow->consumeMotionDown();
5135
5136 ASSERT_TRUE(mDispatcher->waitForIdle());
5137 // Should not ANR because we actually have a focused window. It was just added too slowly.
5138 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5139}
5140
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005141// These tests ensure we cannot send touch events to a window that's positioned behind a window
5142// that has feature NO_INPUT_CHANNEL.
5143// Layout:
5144// Top (closest to user)
5145// mNoInputWindow (above all windows)
5146// mBottomWindow
5147// Bottom (furthest from user)
5148class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5149 virtual void SetUp() override {
5150 InputDispatcherTest::SetUp();
5151
5152 mApplication = std::make_shared<FakeApplicationHandle>();
5153 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5154 "Window without input channel", ADISPLAY_ID_DEFAULT,
5155 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5156
chaviw3277faf2021-05-19 16:45:23 -05005157 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005158 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5159 // It's perfectly valid for this window to not have an associated input channel
5160
5161 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5162 ADISPLAY_ID_DEFAULT);
5163 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5164
5165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5166 }
5167
5168protected:
5169 std::shared_ptr<FakeApplicationHandle> mApplication;
5170 sp<FakeWindowHandle> mNoInputWindow;
5171 sp<FakeWindowHandle> mBottomWindow;
5172};
5173
5174TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5175 PointF touchedPoint = {10, 10};
5176
5177 NotifyMotionArgs motionArgs =
5178 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5179 ADISPLAY_ID_DEFAULT, {touchedPoint});
5180 mDispatcher->notifyMotion(&motionArgs);
5181
5182 mNoInputWindow->assertNoEvents();
5183 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5184 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5185 // and therefore should prevent mBottomWindow from receiving touches
5186 mBottomWindow->assertNoEvents();
5187}
5188
5189/**
5190 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5191 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5192 */
5193TEST_F(InputDispatcherMultiWindowOcclusionTests,
5194 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5195 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5196 "Window with input channel and NO_INPUT_CHANNEL",
5197 ADISPLAY_ID_DEFAULT);
5198
chaviw3277faf2021-05-19 16:45:23 -05005199 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005200 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5202
5203 PointF touchedPoint = {10, 10};
5204
5205 NotifyMotionArgs motionArgs =
5206 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5207 ADISPLAY_ID_DEFAULT, {touchedPoint});
5208 mDispatcher->notifyMotion(&motionArgs);
5209
5210 mNoInputWindow->assertNoEvents();
5211 mBottomWindow->assertNoEvents();
5212}
5213
Vishnu Nair958da932020-08-21 17:12:37 -07005214class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5215protected:
5216 std::shared_ptr<FakeApplicationHandle> mApp;
5217 sp<FakeWindowHandle> mWindow;
5218 sp<FakeWindowHandle> mMirror;
5219
5220 virtual void SetUp() override {
5221 InputDispatcherTest::SetUp();
5222 mApp = std::make_shared<FakeApplicationHandle>();
5223 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5224 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5225 mWindow->getToken());
5226 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5227 mWindow->setFocusable(true);
5228 mMirror->setFocusable(true);
5229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5230 }
5231};
5232
5233TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5234 // Request focus on a mirrored window
5235 setFocusedWindow(mMirror);
5236
5237 // window gets focused
5238 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5240 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005241 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5242}
5243
5244// A focused & mirrored window remains focused only if the window and its mirror are both
5245// focusable.
5246TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5247 setFocusedWindow(mMirror);
5248
5249 // window gets focused
5250 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5252 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005253 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5255 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005256 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5257
5258 mMirror->setFocusable(false);
5259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5260
5261 // window loses focus since one of the windows associated with the token in not focusable
5262 mWindow->consumeFocusEvent(false);
5263
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005264 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5265 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005266 mWindow->assertNoEvents();
5267}
5268
5269// A focused & mirrored window remains focused until the window and its mirror both become
5270// invisible.
5271TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5272 setFocusedWindow(mMirror);
5273
5274 // window gets focused
5275 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5277 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005278 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005279 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5280 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005281 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5282
5283 mMirror->setVisible(false);
5284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5285
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5287 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005288 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5290 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005291 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5292
5293 mWindow->setVisible(false);
5294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5295
5296 // window loses focus only after all windows associated with the token become invisible.
5297 mWindow->consumeFocusEvent(false);
5298
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005299 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5300 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005301 mWindow->assertNoEvents();
5302}
5303
5304// A focused & mirrored window remains focused until both windows are removed.
5305TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5306 setFocusedWindow(mMirror);
5307
5308 // window gets focused
5309 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5311 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005312 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5314 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005315 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5316
5317 // single window is removed but the window token remains focused
5318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5319
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5321 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005322 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5324 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005325 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5326
5327 // Both windows are removed
5328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5329 mWindow->consumeFocusEvent(false);
5330
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005331 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5332 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005333 mWindow->assertNoEvents();
5334}
5335
5336// Focus request can be pending until one window becomes visible.
5337TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5338 // Request focus on an invisible mirror.
5339 mWindow->setVisible(false);
5340 mMirror->setVisible(false);
5341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5342 setFocusedWindow(mMirror);
5343
5344 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005346 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005347 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005348
5349 mMirror->setVisible(true);
5350 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5351
5352 // window gets focused
5353 mWindow->consumeFocusEvent(true);
5354 // window gets the pending key event
5355 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5356}
Prabir Pradhan99987712020-11-10 18:43:05 -08005357
5358class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5359protected:
5360 std::shared_ptr<FakeApplicationHandle> mApp;
5361 sp<FakeWindowHandle> mWindow;
5362 sp<FakeWindowHandle> mSecondWindow;
5363
5364 void SetUp() override {
5365 InputDispatcherTest::SetUp();
5366 mApp = std::make_shared<FakeApplicationHandle>();
5367 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5368 mWindow->setFocusable(true);
5369 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5370 mSecondWindow->setFocusable(true);
5371
5372 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5374
5375 setFocusedWindow(mWindow);
5376 mWindow->consumeFocusEvent(true);
5377 }
5378
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005379 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5380 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005381 mDispatcher->notifyPointerCaptureChanged(&args);
5382 }
5383
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005384 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5385 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005386 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005387 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5388 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005389 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005390 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005391 }
5392};
5393
5394TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5395 // Ensure that capture cannot be obtained for unfocused windows.
5396 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5397 mFakePolicy->assertSetPointerCaptureNotCalled();
5398 mSecondWindow->assertNoEvents();
5399
5400 // Ensure that capture can be enabled from the focus window.
5401 requestAndVerifyPointerCapture(mWindow, true);
5402
5403 // Ensure that capture cannot be disabled from a window that does not have capture.
5404 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5405 mFakePolicy->assertSetPointerCaptureNotCalled();
5406
5407 // Ensure that capture can be disabled from the window with capture.
5408 requestAndVerifyPointerCapture(mWindow, false);
5409}
5410
5411TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005412 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005413
5414 setFocusedWindow(mSecondWindow);
5415
5416 // Ensure that the capture disabled event was sent first.
5417 mWindow->consumeCaptureEvent(false);
5418 mWindow->consumeFocusEvent(false);
5419 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005420 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005421
5422 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005423 notifyPointerCaptureChanged({});
5424 notifyPointerCaptureChanged(request);
5425 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005426 mWindow->assertNoEvents();
5427 mSecondWindow->assertNoEvents();
5428 mFakePolicy->assertSetPointerCaptureNotCalled();
5429}
5430
5431TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005432 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005433
5434 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005435 notifyPointerCaptureChanged({});
5436 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005437
5438 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005439 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005440 mWindow->consumeCaptureEvent(false);
5441 mWindow->assertNoEvents();
5442}
5443
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005444TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5445 requestAndVerifyPointerCapture(mWindow, true);
5446
5447 // The first window loses focus.
5448 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005449 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005450 mWindow->consumeCaptureEvent(false);
5451
5452 // Request Pointer Capture from the second window before the notification from InputReader
5453 // arrives.
5454 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005455 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005456
5457 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005458 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005459
5460 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005461 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005462
5463 mSecondWindow->consumeFocusEvent(true);
5464 mSecondWindow->consumeCaptureEvent(true);
5465}
5466
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005467TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5468 // App repeatedly enables and disables capture.
5469 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5470 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5471 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5472 mFakePolicy->assertSetPointerCaptureCalled(false);
5473 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5474 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5475
5476 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5477 // first request is now stale, this should do nothing.
5478 notifyPointerCaptureChanged(firstRequest);
5479 mWindow->assertNoEvents();
5480
5481 // InputReader notifies that the second request was enabled.
5482 notifyPointerCaptureChanged(secondRequest);
5483 mWindow->consumeCaptureEvent(true);
5484}
5485
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005486class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5487protected:
5488 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005489
5490 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5491 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5492
5493 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5494 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5495
5496 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5497 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5498 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5499 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5500 MAXIMUM_OBSCURING_OPACITY);
5501
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005502 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005503 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005504 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005505
5506 sp<FakeWindowHandle> mTouchWindow;
5507
5508 virtual void SetUp() override {
5509 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005510 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005511 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5512 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5513 }
5514
5515 virtual void TearDown() override {
5516 InputDispatcherTest::TearDown();
5517 mTouchWindow.clear();
5518 }
5519
chaviw3277faf2021-05-19 16:45:23 -05005520 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5521 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005522 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005523 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005524 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005525 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005526 return window;
5527 }
5528
5529 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5530 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5531 sp<FakeWindowHandle> window =
5532 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5533 // Generate an arbitrary PID based on the UID
5534 window->setOwnerInfo(1777 + (uid % 10000), uid);
5535 return window;
5536 }
5537
5538 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5539 NotifyMotionArgs args =
5540 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5541 ADISPLAY_ID_DEFAULT, points);
5542 mDispatcher->notifyMotion(&args);
5543 }
5544};
5545
5546TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005547 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005548 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005550
5551 touch();
5552
5553 mTouchWindow->assertNoEvents();
5554}
5555
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005556TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005557 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5558 const sp<FakeWindowHandle>& w =
5559 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5561
5562 touch();
5563
5564 mTouchWindow->assertNoEvents();
5565}
5566
5567TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005568 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5569 const sp<FakeWindowHandle>& w =
5570 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5572
5573 touch();
5574
5575 w->assertNoEvents();
5576}
5577
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005578TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005579 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005581
5582 touch();
5583
5584 mTouchWindow->consumeAnyMotionDown();
5585}
5586
5587TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005588 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005589 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005590 w->setFrame(Rect(0, 0, 50, 50));
5591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005592
5593 touch({PointF{100, 100}});
5594
5595 mTouchWindow->consumeAnyMotionDown();
5596}
5597
5598TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005599 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005600 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5602
5603 touch();
5604
5605 mTouchWindow->consumeAnyMotionDown();
5606}
5607
5608TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5609 const sp<FakeWindowHandle>& w =
5610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005612
5613 touch();
5614
5615 mTouchWindow->consumeAnyMotionDown();
5616}
5617
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005618TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5619 const sp<FakeWindowHandle>& w =
5620 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5622
5623 touch();
5624
5625 w->assertNoEvents();
5626}
5627
5628/**
5629 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5630 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5631 * window, the occluding window will still receive ACTION_OUTSIDE event.
5632 */
5633TEST_F(InputDispatcherUntrustedTouchesTest,
5634 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5635 const sp<FakeWindowHandle>& w =
5636 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005637 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5639
5640 touch();
5641
5642 w->consumeMotionOutside();
5643}
5644
5645TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5646 const sp<FakeWindowHandle>& w =
5647 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005648 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5650
5651 touch();
5652
5653 InputEvent* event = w->consume();
5654 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5655 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5656 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5657 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5658}
5659
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005660TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005661 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005662 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5663 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5665
5666 touch();
5667
5668 mTouchWindow->consumeAnyMotionDown();
5669}
5670
5671TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5672 const sp<FakeWindowHandle>& w =
5673 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5674 MAXIMUM_OBSCURING_OPACITY);
5675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005676
5677 touch();
5678
5679 mTouchWindow->consumeAnyMotionDown();
5680}
5681
5682TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005683 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5685 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5687
5688 touch();
5689
5690 mTouchWindow->assertNoEvents();
5691}
5692
5693TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5694 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5695 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005696 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5697 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005698 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005699 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5700 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5702
5703 touch();
5704
5705 mTouchWindow->assertNoEvents();
5706}
5707
5708TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5709 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5710 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005711 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5712 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005713 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005714 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5715 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5717
5718 touch();
5719
5720 mTouchWindow->consumeAnyMotionDown();
5721}
5722
5723TEST_F(InputDispatcherUntrustedTouchesTest,
5724 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5725 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005726 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5727 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005728 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005729 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5730 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5732
5733 touch();
5734
5735 mTouchWindow->consumeAnyMotionDown();
5736}
5737
5738TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5739 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005740 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5741 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005742 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005743 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5744 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005746
5747 touch();
5748
5749 mTouchWindow->assertNoEvents();
5750}
5751
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005752TEST_F(InputDispatcherUntrustedTouchesTest,
5753 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5754 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005755 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5756 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005757 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005758 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5759 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5761
5762 touch();
5763
5764 mTouchWindow->assertNoEvents();
5765}
5766
5767TEST_F(InputDispatcherUntrustedTouchesTest,
5768 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5769 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005770 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5771 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005772 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005773 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5774 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5776
5777 touch();
5778
5779 mTouchWindow->consumeAnyMotionDown();
5780}
5781
5782TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5783 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005784 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5785 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5787
5788 touch();
5789
5790 mTouchWindow->consumeAnyMotionDown();
5791}
5792
5793TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5794 const sp<FakeWindowHandle>& w =
5795 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5797
5798 touch();
5799
5800 mTouchWindow->consumeAnyMotionDown();
5801}
5802
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005803TEST_F(InputDispatcherUntrustedTouchesTest,
5804 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5805 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5806 const sp<FakeWindowHandle>& w =
5807 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5809
5810 touch();
5811
5812 mTouchWindow->assertNoEvents();
5813}
5814
5815TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5816 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5817 const sp<FakeWindowHandle>& w =
5818 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5820
5821 touch();
5822
5823 mTouchWindow->consumeAnyMotionDown();
5824}
5825
5826TEST_F(InputDispatcherUntrustedTouchesTest,
5827 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5828 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5829 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005830 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5831 OPACITY_ABOVE_THRESHOLD);
5832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5833
5834 touch();
5835
5836 mTouchWindow->consumeAnyMotionDown();
5837}
5838
5839TEST_F(InputDispatcherUntrustedTouchesTest,
5840 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5841 const sp<FakeWindowHandle>& w1 =
5842 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5843 OPACITY_BELOW_THRESHOLD);
5844 const sp<FakeWindowHandle>& w2 =
5845 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5846 OPACITY_BELOW_THRESHOLD);
5847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5848
5849 touch();
5850
5851 mTouchWindow->assertNoEvents();
5852}
5853
5854/**
5855 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5856 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5857 * (which alone would result in allowing touches) does not affect the blocking behavior.
5858 */
5859TEST_F(InputDispatcherUntrustedTouchesTest,
5860 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5861 const sp<FakeWindowHandle>& wB =
5862 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5863 OPACITY_BELOW_THRESHOLD);
5864 const sp<FakeWindowHandle>& wC =
5865 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5866 OPACITY_BELOW_THRESHOLD);
5867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5868
5869 touch();
5870
5871 mTouchWindow->assertNoEvents();
5872}
5873
5874/**
5875 * This test is testing that a window from a different UID but with same application token doesn't
5876 * block the touch. Apps can share the application token for close UI collaboration for example.
5877 */
5878TEST_F(InputDispatcherUntrustedTouchesTest,
5879 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5880 const sp<FakeWindowHandle>& w =
5881 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5882 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5884
5885 touch();
5886
5887 mTouchWindow->consumeAnyMotionDown();
5888}
5889
arthurhungb89ccb02020-12-30 16:19:01 +08005890class InputDispatcherDragTests : public InputDispatcherTest {
5891protected:
5892 std::shared_ptr<FakeApplicationHandle> mApp;
5893 sp<FakeWindowHandle> mWindow;
5894 sp<FakeWindowHandle> mSecondWindow;
5895 sp<FakeWindowHandle> mDragWindow;
5896
5897 void SetUp() override {
5898 InputDispatcherTest::SetUp();
5899 mApp = std::make_shared<FakeApplicationHandle>();
5900 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5901 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005902 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005903
5904 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5905 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005906 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005907
5908 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5910 }
5911
5912 // Start performing drag, we will create a drag window and transfer touch to it.
5913 void performDrag() {
5914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5915 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5916 {50, 50}))
5917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5918
5919 // Window should receive motion event.
5920 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5921
5922 // The drag window covers the entire display
5923 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5924 mDispatcher->setInputWindows(
5925 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5926
5927 // Transfer touch focus to the drag window
5928 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5929 true /* isDragDrop */);
5930 mWindow->consumeMotionCancel();
5931 mDragWindow->consumeMotionDown();
5932 }
arthurhung6d4bed92021-03-17 11:59:33 +08005933
5934 // Start performing drag, we will create a drag window and transfer touch to it.
5935 void performStylusDrag() {
5936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5937 injectMotionEvent(mDispatcher,
5938 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5939 AINPUT_SOURCE_STYLUS)
5940 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5941 .pointer(PointerBuilder(0,
5942 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5943 .x(50)
5944 .y(50))
5945 .build()));
5946 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5947
5948 // The drag window covers the entire display
5949 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5950 mDispatcher->setInputWindows(
5951 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5952
5953 // Transfer touch focus to the drag window
5954 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5955 true /* isDragDrop */);
5956 mWindow->consumeMotionCancel();
5957 mDragWindow->consumeMotionDown();
5958 }
arthurhungb89ccb02020-12-30 16:19:01 +08005959};
5960
5961TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5962 performDrag();
5963
5964 // Move on window.
5965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5966 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5967 ADISPLAY_ID_DEFAULT, {50, 50}))
5968 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5969 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5970 mWindow->consumeDragEvent(false, 50, 50);
5971 mSecondWindow->assertNoEvents();
5972
5973 // Move to another window.
5974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5976 ADISPLAY_ID_DEFAULT, {150, 50}))
5977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5978 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5979 mWindow->consumeDragEvent(true, 150, 50);
5980 mSecondWindow->consumeDragEvent(false, 50, 50);
5981
5982 // Move back to original window.
5983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5984 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5985 ADISPLAY_ID_DEFAULT, {50, 50}))
5986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5987 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5988 mWindow->consumeDragEvent(false, 50, 50);
5989 mSecondWindow->consumeDragEvent(true, -50, 50);
5990
5991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5992 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5994 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5995 mWindow->assertNoEvents();
5996 mSecondWindow->assertNoEvents();
5997}
5998
arthurhungf452d0b2021-01-06 00:19:52 +08005999TEST_F(InputDispatcherDragTests, DragAndDrop) {
6000 performDrag();
6001
6002 // Move on window.
6003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6004 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6005 ADISPLAY_ID_DEFAULT, {50, 50}))
6006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6007 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6008 mWindow->consumeDragEvent(false, 50, 50);
6009 mSecondWindow->assertNoEvents();
6010
6011 // Move to another window.
6012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6013 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6014 ADISPLAY_ID_DEFAULT, {150, 50}))
6015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6016 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6017 mWindow->consumeDragEvent(true, 150, 50);
6018 mSecondWindow->consumeDragEvent(false, 50, 50);
6019
6020 // drop to another window.
6021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6022 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6023 {150, 50}))
6024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6025 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6026 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6027 mWindow->assertNoEvents();
6028 mSecondWindow->assertNoEvents();
6029}
6030
arthurhung6d4bed92021-03-17 11:59:33 +08006031TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6032 performStylusDrag();
6033
6034 // Move on window and keep button pressed.
6035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6036 injectMotionEvent(mDispatcher,
6037 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6038 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6040 .x(50)
6041 .y(50))
6042 .build()))
6043 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6044 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6045 mWindow->consumeDragEvent(false, 50, 50);
6046 mSecondWindow->assertNoEvents();
6047
6048 // Move to another window and release button, expect to drop item.
6049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6050 injectMotionEvent(mDispatcher,
6051 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6052 .buttonState(0)
6053 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6054 .x(150)
6055 .y(50))
6056 .build()))
6057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6058 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6059 mWindow->assertNoEvents();
6060 mSecondWindow->assertNoEvents();
6061 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6062
6063 // nothing to the window.
6064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6065 injectMotionEvent(mDispatcher,
6066 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6067 .buttonState(0)
6068 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6069 .x(150)
6070 .y(50))
6071 .build()))
6072 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6073 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6074 mWindow->assertNoEvents();
6075 mSecondWindow->assertNoEvents();
6076}
6077
Arthur Hung6d0571e2021-04-09 20:18:16 +08006078TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6079 performDrag();
6080
6081 // Set second window invisible.
6082 mSecondWindow->setVisible(false);
6083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6084
6085 // Move on window.
6086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6087 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6088 ADISPLAY_ID_DEFAULT, {50, 50}))
6089 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6090 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6091 mWindow->consumeDragEvent(false, 50, 50);
6092 mSecondWindow->assertNoEvents();
6093
6094 // Move to another window.
6095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6096 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6097 ADISPLAY_ID_DEFAULT, {150, 50}))
6098 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6099 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6100 mWindow->consumeDragEvent(true, 150, 50);
6101 mSecondWindow->assertNoEvents();
6102
6103 // drop to another window.
6104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6105 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6106 {150, 50}))
6107 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6108 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6109 mFakePolicy->assertDropTargetEquals(nullptr);
6110 mWindow->assertNoEvents();
6111 mSecondWindow->assertNoEvents();
6112}
6113
Vishnu Nair062a8672021-09-03 16:07:44 -07006114class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6115
6116TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6117 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6118 sp<FakeWindowHandle> window =
6119 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6120 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6121 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6122 window->setFocusable(true);
6123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6124 setFocusedWindow(window);
6125 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6126
6127 // With the flag set, window should not get any input
6128 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6129 mDispatcher->notifyKey(&keyArgs);
6130 window->assertNoEvents();
6131
6132 NotifyMotionArgs motionArgs =
6133 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6134 ADISPLAY_ID_DEFAULT);
6135 mDispatcher->notifyMotion(&motionArgs);
6136 window->assertNoEvents();
6137
6138 // With the flag cleared, the window should get input
6139 window->setInputFeatures({});
6140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6141
6142 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6143 mDispatcher->notifyKey(&keyArgs);
6144 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6145
6146 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6147 ADISPLAY_ID_DEFAULT);
6148 mDispatcher->notifyMotion(&motionArgs);
6149 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6150 window->assertNoEvents();
6151}
6152
6153TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6154 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6155 std::make_shared<FakeApplicationHandle>();
6156 sp<FakeWindowHandle> obscuringWindow =
6157 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6158 ADISPLAY_ID_DEFAULT);
6159 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6160 obscuringWindow->setOwnerInfo(111, 111);
6161 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6162 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6163 sp<FakeWindowHandle> window =
6164 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6165 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6166 window->setOwnerInfo(222, 222);
6167 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6168 window->setFocusable(true);
6169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6170 setFocusedWindow(window);
6171 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6172
6173 // With the flag set, window should not get any input
6174 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6175 mDispatcher->notifyKey(&keyArgs);
6176 window->assertNoEvents();
6177
6178 NotifyMotionArgs motionArgs =
6179 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6180 ADISPLAY_ID_DEFAULT);
6181 mDispatcher->notifyMotion(&motionArgs);
6182 window->assertNoEvents();
6183
6184 // With the flag cleared, the window should get input
6185 window->setInputFeatures({});
6186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6187
6188 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6189 mDispatcher->notifyKey(&keyArgs);
6190 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6191
6192 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6193 ADISPLAY_ID_DEFAULT);
6194 mDispatcher->notifyMotion(&motionArgs);
6195 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6196 window->assertNoEvents();
6197}
6198
6199TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6200 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6201 std::make_shared<FakeApplicationHandle>();
6202 sp<FakeWindowHandle> obscuringWindow =
6203 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6204 ADISPLAY_ID_DEFAULT);
6205 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6206 obscuringWindow->setOwnerInfo(111, 111);
6207 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6208 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6209 sp<FakeWindowHandle> window =
6210 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6211 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6212 window->setOwnerInfo(222, 222);
6213 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6214 window->setFocusable(true);
6215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6216 setFocusedWindow(window);
6217 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6218
6219 // With the flag set, window should not get any input
6220 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6221 mDispatcher->notifyKey(&keyArgs);
6222 window->assertNoEvents();
6223
6224 NotifyMotionArgs motionArgs =
6225 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6226 ADISPLAY_ID_DEFAULT);
6227 mDispatcher->notifyMotion(&motionArgs);
6228 window->assertNoEvents();
6229
6230 // When the window is no longer obscured because it went on top, it should get input
6231 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6232
6233 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6234 mDispatcher->notifyKey(&keyArgs);
6235 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6236
6237 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6238 ADISPLAY_ID_DEFAULT);
6239 mDispatcher->notifyMotion(&motionArgs);
6240 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6241 window->assertNoEvents();
6242}
6243
Antonio Kantekf16f2832021-09-28 04:39:20 +00006244class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6245protected:
6246 std::shared_ptr<FakeApplicationHandle> mApp;
6247 sp<FakeWindowHandle> mWindow;
6248 sp<FakeWindowHandle> mSecondWindow;
6249
6250 void SetUp() override {
6251 InputDispatcherTest::SetUp();
6252
6253 mApp = std::make_shared<FakeApplicationHandle>();
6254 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6255 mWindow->setFocusable(true);
6256 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6257 mSecondWindow->setFocusable(true);
6258
6259 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6261
6262 setFocusedWindow(mWindow);
6263 mWindow->consumeFocusEvent(true);
6264 }
6265
6266 void changeAndVerifyTouchMode(bool inTouchMode) {
6267 mDispatcher->setInTouchMode(inTouchMode);
6268 mWindow->consumeTouchModeEvent(inTouchMode);
6269 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6270 }
6271};
6272
6273TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6274 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6275}
6276
6277TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6278 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6279 mWindow->assertNoEvents();
6280 mSecondWindow->assertNoEvents();
6281}
6282
Garfield Tane84e6f92019-08-29 17:28:41 -07006283} // namespace android::inputdispatcher