blob: 3207495aaf710520964be74174fbafe183941ebd [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) {
222 const std::chrono::time_point start = std::chrono::steady_clock::now();
223 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700224
225 // If there is an ANR, Dispatcher won't be idle because there are still events
226 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
227 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500228 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
229 // to provide it some time to act. 100ms seems reasonable.
230 mNotifyAnr.wait_for(lock, timeToWait,
231 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700232 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500233 if (storage.empty()) {
234 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700236 }
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 Vishniakou234129c2020-10-22 22:28:12 -0500246 T token = storage.front();
247 storage.pop();
248 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700249 }
250
251 void assertNotifyAnrWasNotCalled() {
252 std::scoped_lock lock(mLock);
253 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000254 ASSERT_TRUE(mAnrWindowTokens.empty());
255 ASSERT_TRUE(mAnrMonitorPids.empty());
256 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500257 << "ANR was not called, but please also consume the 'connection is responsive' "
258 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000259 ASSERT_TRUE(mResponsiveMonitorPids.empty())
260 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
261 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700262 }
263
Garfield Tan1c7bc862020-01-28 13:24:04 -0800264 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
265 mConfig.keyRepeatTimeout = timeout;
266 mConfig.keyRepeatDelay = delay;
267 }
268
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000269 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800270 std::unique_lock lock(mLock);
271 base::ScopedLockAssertion assumeLocked(mLock);
272
273 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
274 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000275 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800276 enabled;
277 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
279 << ") to be called.";
280 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000282 auto request = *mPointerCaptureRequest;
283 mPointerCaptureRequest.reset();
284 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800285 }
286
287 void assertSetPointerCaptureNotCalled() {
288 std::unique_lock lock(mLock);
289 base::ScopedLockAssertion assumeLocked(mLock);
290
291 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000292 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800293 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000294 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800295 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000296 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800297 }
298
arthurhungf452d0b2021-01-06 00:19:52 +0800299 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
300 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800301 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800302 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800303 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800304 }
305
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700307 std::mutex mLock;
308 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
309 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
310 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
311 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800312
Prabir Pradhan99987712020-11-10 18:43:05 -0800313 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000314
315 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800316
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700317 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700318 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000319 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
320 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
321 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
322 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700323 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700324
arthurhungf452d0b2021-01-06 00:19:52 +0800325 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800326 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800327
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600328 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700329 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800330 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331 }
332
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000333 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700334 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000335 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700336 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500337 }
338
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000339 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500340 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000341 mAnrMonitorPids.push(pid);
342 mNotifyAnr.notify_all();
343 }
344
345 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
346 std::scoped_lock lock(mLock);
347 mResponsiveWindowTokens.push(connectionToken);
348 mNotifyAnr.notify_all();
349 }
350
351 void notifyMonitorResponsive(int32_t pid) override {
352 std::scoped_lock lock(mLock);
353 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500354 mNotifyAnr.notify_all();
355 }
356
357 void notifyNoFocusedWindowAnr(
358 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
359 std::scoped_lock lock(mLock);
360 mAnrApplications.push(applicationHandle);
361 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362 }
363
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600364 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600366 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700367
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600368 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700369 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
370 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
371 const std::vector<float>& values) override {}
372
373 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
374 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000375
Chris Yefb552902021-02-03 17:18:37 -0800376 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
377
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600378 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379 *outConfig = mConfig;
380 }
381
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600382 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700383 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800384 switch (inputEvent->getType()) {
385 case AINPUT_EVENT_TYPE_KEY: {
386 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800387 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800388 break;
389 }
390
391 case AINPUT_EVENT_TYPE_MOTION: {
392 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800393 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800394 break;
395 }
396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397 return true;
398 }
399
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600400 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600402 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600404 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 return 0;
406 }
407
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600408 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 return false;
410 }
411
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600412 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
413 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700414 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800415 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
416 * essentially a passthrough for notifySwitch.
417 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800418 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 }
420
Sean Stoutb4e0a592021-02-23 07:34:53 -0800421 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800423 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
424 return pid == INJECTOR_PID && uid == INJECTOR_UID;
425 }
Jackal Guof9696682018-10-05 12:23:23 +0800426
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600427 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700428 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700429 mOnPointerDownToken = newToken;
430 }
431
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000432 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800433 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000434 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800435 mPointerCaptureChangedCondition.notify_all();
436 }
437
arthurhungf452d0b2021-01-06 00:19:52 +0800438 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
439 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800440 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800441 mDropTargetWindowToken = token;
442 }
443
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700444 void assertFilterInputEventWasCalledInternal(
445 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700446 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800447 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700448 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800449 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451};
452
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453// --- InputDispatcherTest ---
454
455class InputDispatcherTest : public testing::Test {
456protected:
457 sp<FakeInputDispatcherPolicy> mFakePolicy;
458 sp<InputDispatcher> mDispatcher;
459
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000460 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 mFakePolicy = new FakeInputDispatcherPolicy();
462 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800463 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000464 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700465 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 }
467
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700469 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 mFakePolicy.clear();
471 mDispatcher.clear();
472 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700473
474 /**
475 * Used for debugging when writing the test
476 */
477 void dumpDispatcherState() {
478 std::string dump;
479 mDispatcher->dump(dump);
480 std::stringstream ss(dump);
481 std::string to;
482
483 while (std::getline(ss, to, '\n')) {
484 ALOGE("%s", to.c_str());
485 }
486 }
Vishnu Nair958da932020-08-21 17:12:37 -0700487
chaviw3277faf2021-05-19 16:45:23 -0500488 void setFocusedWindow(const sp<WindowInfoHandle>& window,
489 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700490 FocusRequest request;
491 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000492 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700493 if (focusedWindow) {
494 request.focusedToken = focusedWindow->getToken();
495 }
496 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
497 request.displayId = window->getInfo()->displayId;
498 mDispatcher->setFocusedWindow(request);
499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500};
501
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
503 KeyEvent event;
504
505 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800506 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
507 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600508 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
509 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800510 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700511 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800512 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 << "Should reject key events with undefined action.";
514
515 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800516 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
517 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600518 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800519 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700520 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800521 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 << "Should reject key events with ACTION_MULTIPLE.";
523}
524
525TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
526 MotionEvent event;
527 PointerProperties pointerProperties[MAX_POINTERS + 1];
528 PointerCoords pointerCoords[MAX_POINTERS + 1];
529 for (int i = 0; i <= MAX_POINTERS; i++) {
530 pointerProperties[i].clear();
531 pointerProperties[i].id = i;
532 pointerCoords[i].clear();
533 }
534
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800535 // Some constants commonly used below
536 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
537 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
538 constexpr int32_t metaState = AMETA_NONE;
539 constexpr MotionClassification classification = MotionClassification::NONE;
540
chaviw9eaa22c2020-07-01 16:21:27 -0700541 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800543 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700544 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
545 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700546 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
547 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700548 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800549 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700550 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 << "Should reject motion events with undefined action.";
553
554 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800555 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700556 AMOTION_EVENT_ACTION_POINTER_DOWN |
557 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700558 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
559 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700560 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500561 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800562 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700563 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800564 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 << "Should reject motion events with pointer down index too large.";
566
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 AMOTION_EVENT_ACTION_POINTER_DOWN |
569 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700570 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
571 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700572 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500573 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700575 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 << "Should reject motion events with pointer down index too small.";
578
579 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800580 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700581 AMOTION_EVENT_ACTION_POINTER_UP |
582 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700583 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
584 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700585 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500586 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800587 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700588 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800589 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 << "Should reject motion events with pointer up index too large.";
591
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700593 AMOTION_EVENT_ACTION_POINTER_UP |
594 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700595 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
596 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700597 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500598 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700600 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800601 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject motion events with pointer up index too small.";
603
604 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
606 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700607 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700608 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
609 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700610 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700612 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800613 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 << "Should reject motion events with 0 pointers.";
615
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
617 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700618 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700619 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
620 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with more than MAX_POINTERS pointers.";
626
627 // Rejects motion events with invalid pointer ids.
628 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
630 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700631 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700632 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
633 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700634 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700636 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800637 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 << "Should reject motion events with pointer ids less than 0.";
639
640 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800641 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
642 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700643 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700644 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
645 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700646 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700648 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800649 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
651
652 // Rejects motion events with duplicate pointer ids.
653 pointerProperties[0].id = 1;
654 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800655 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
656 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700657 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700658 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
659 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800661 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700662 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800663 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 << "Should reject motion events with duplicate pointer ids.";
665}
666
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800667/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
668
669TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
670 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800671 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800672 mDispatcher->notifyConfigurationChanged(&args);
673 ASSERT_TRUE(mDispatcher->waitForIdle());
674
675 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
676}
677
678TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800679 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
680 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800681 mDispatcher->notifySwitch(&args);
682
683 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
684 args.policyFlags |= POLICY_FLAG_TRUSTED;
685 mFakePolicy->assertNotifySwitchWasCalled(args);
686}
687
Arthur Hungb92218b2018-08-14 12:00:21 +0800688// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700689static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700690// Default input dispatching timeout if there is no focused application or paused window
691// from which to determine an appropriate dispatching timeout.
692static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
693 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
694 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800695
696class FakeApplicationHandle : public InputApplicationHandle {
697public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700698 FakeApplicationHandle() {
699 mInfo.name = "Fake Application";
700 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500701 mInfo.dispatchingTimeoutMillis =
702 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700703 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800704 virtual ~FakeApplicationHandle() {}
705
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000706 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700707
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500708 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
709 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700710 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800711};
712
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800713class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800714public:
Garfield Tan15601662020-09-22 15:32:38 -0700715 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800716 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700717 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800718 }
719
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800720 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700721 InputEvent* event;
722 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
723 if (!consumeSeq) {
724 return nullptr;
725 }
726 finishEvent(*consumeSeq);
727 return event;
728 }
729
730 /**
731 * Receive an event without acknowledging it.
732 * Return the sequence number that could later be used to send finished signal.
733 */
734 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800735 uint32_t consumeSeq;
736 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800737
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800738 std::chrono::time_point start = std::chrono::steady_clock::now();
739 status_t status = WOULD_BLOCK;
740 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800741 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800742 &event);
743 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
744 if (elapsed > 100ms) {
745 break;
746 }
747 }
748
749 if (status == WOULD_BLOCK) {
750 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800752 }
753
754 if (status != OK) {
755 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700756 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800757 }
758 if (event == nullptr) {
759 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700760 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800761 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700762 if (outEvent != nullptr) {
763 *outEvent = event;
764 }
765 return consumeSeq;
766 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700768 /**
769 * To be used together with "receiveEvent" to complete the consumption of an event.
770 */
771 void finishEvent(uint32_t consumeSeq) {
772 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
773 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800774 }
775
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000776 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
777 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
778 ASSERT_EQ(OK, status);
779 }
780
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000781 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
782 std::optional<int32_t> expectedDisplayId,
783 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800784 InputEvent* event = consume();
785
786 ASSERT_NE(nullptr, event) << mName.c_str()
787 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800788 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700789 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800790 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800791
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000792 if (expectedDisplayId.has_value()) {
793 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
794 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800795
Tiger Huang8664f8c2018-10-11 19:14:35 +0800796 switch (expectedEventType) {
797 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800798 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
799 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000800 if (expectedFlags.has_value()) {
801 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
802 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800803 break;
804 }
805 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800806 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000807 assertMotionAction(expectedAction, motionEvent.getAction());
808
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000809 if (expectedFlags.has_value()) {
810 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
811 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800812 break;
813 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100814 case AINPUT_EVENT_TYPE_FOCUS: {
815 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
816 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800817 case AINPUT_EVENT_TYPE_CAPTURE: {
818 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
819 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000820 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
821 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
822 }
arthurhungb89ccb02020-12-30 16:19:01 +0800823 case AINPUT_EVENT_TYPE_DRAG: {
824 FAIL() << "Use 'consumeDragEvent' for DRAG events";
825 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826 default: {
827 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
828 }
829 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800830 }
831
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100832 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
833 InputEvent* event = consume();
834 ASSERT_NE(nullptr, event) << mName.c_str()
835 << ": consumer should have returned non-NULL event.";
836 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
837 << "Got " << inputEventTypeToString(event->getType())
838 << " event instead of FOCUS event";
839
840 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
841 << mName.c_str() << ": event displayId should always be NONE.";
842
843 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
844 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
845 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
846 }
847
Prabir Pradhan99987712020-11-10 18:43:05 -0800848 void consumeCaptureEvent(bool hasCapture) {
849 const InputEvent* event = consume();
850 ASSERT_NE(nullptr, event) << mName.c_str()
851 << ": consumer should have returned non-NULL event.";
852 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
853 << "Got " << inputEventTypeToString(event->getType())
854 << " event instead of CAPTURE event";
855
856 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
857 << mName.c_str() << ": event displayId should always be NONE.";
858
859 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
860 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
861 }
862
arthurhungb89ccb02020-12-30 16:19:01 +0800863 void consumeDragEvent(bool isExiting, float x, float y) {
864 const 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_DRAG, event->getType())
868 << "Got " << inputEventTypeToString(event->getType())
869 << " event instead of DRAG event";
870
871 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
872 << mName.c_str() << ": event displayId should always be NONE.";
873
874 const auto& dragEvent = static_cast<const DragEvent&>(*event);
875 EXPECT_EQ(isExiting, dragEvent.isExiting());
876 EXPECT_EQ(x, dragEvent.getX());
877 EXPECT_EQ(y, dragEvent.getY());
878 }
879
Antonio Kantekf16f2832021-09-28 04:39:20 +0000880 void consumeTouchModeEvent(bool inTouchMode) {
881 const InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of TOUCH_MODE event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
891 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
892 }
893
chaviwd1c23182019-12-20 18:44:56 -0800894 void assertNoEvents() {
895 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 if (event == nullptr) {
897 return;
898 }
899 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
900 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
901 ADD_FAILURE() << "Received key event "
902 << KeyEvent::actionToString(keyEvent.getAction());
903 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
904 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
905 ADD_FAILURE() << "Received motion event "
906 << MotionEvent::actionToString(motionEvent.getAction());
907 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
908 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
909 ADD_FAILURE() << "Received focus event, hasFocus = "
910 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800911 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
912 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
913 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
914 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000915 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
916 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
917 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
918 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919 }
920 FAIL() << mName.c_str()
921 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800922 }
923
924 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
925
926protected:
927 std::unique_ptr<InputConsumer> mConsumer;
928 PreallocatedInputEventFactory mEventFactory;
929
930 std::string mName;
931};
932
chaviw3277faf2021-05-19 16:45:23 -0500933class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800934public:
935 static const int32_t WIDTH = 600;
936 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800937
Chris Yea209fde2020-07-22 13:54:51 -0700938 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800939 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500940 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800941 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500942 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700943 base::Result<std::unique_ptr<InputChannel>> channel =
944 dispatcher->createInputChannel(name);
945 token = (*channel)->getConnectionToken();
946 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800947 }
948
949 inputApplicationHandle->updateInfo();
950 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
951
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500952 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700953 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800954 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500955 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500956 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000957 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800958 mInfo.frameLeft = 0;
959 mInfo.frameTop = 0;
960 mInfo.frameRight = WIDTH;
961 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700962 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800963 mInfo.globalScaleFactor = 1.0;
964 mInfo.touchableRegion.clear();
965 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
966 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700967 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800968 mInfo.hasWallpaper = false;
969 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800970 mInfo.ownerPid = INJECTOR_PID;
971 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800972 mInfo.displayId = displayId;
973 }
974
Arthur Hungabbb9d82021-09-01 14:52:30 +0000975 sp<FakeWindowHandle> clone(
976 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
977 const sp<InputDispatcher>& dispatcher, int32_t displayId) {
978 sp<FakeWindowHandle> handle =
979 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
980 displayId, mInfo.token);
981 return handle;
982 }
983
Vishnu Nair47074b82020-08-14 11:54:47 -0700984 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800985
Vishnu Nair958da932020-08-21 17:12:37 -0700986 void setVisible(bool visible) { mInfo.visible = visible; }
987
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700988 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500989 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700990 }
991
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 void setPaused(bool paused) { mInfo.paused = paused; }
993
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000994 void setAlpha(float alpha) { mInfo.alpha = alpha; }
995
chaviw3277faf2021-05-19 16:45:23 -0500996 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000997
Bernardo Rufino7393d172021-02-26 13:56:11 +0000998 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
999
chaviwd1c23182019-12-20 18:44:56 -08001000 void setFrame(const Rect& frame) {
1001 mInfo.frameLeft = frame.left;
1002 mInfo.frameTop = frame.top;
1003 mInfo.frameRight = frame.right;
1004 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +08001005 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -08001006 mInfo.touchableRegion.clear();
1007 mInfo.addTouchableRegion(frame);
1008 }
1009
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001010 void setType(WindowInfo::Type type) { mInfo.type = type; }
1011
1012 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1013
chaviw3277faf2021-05-19 16:45:23 -05001014 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001015
chaviw3277faf2021-05-19 16:45:23 -05001016 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001017
chaviw3277faf2021-05-19 16:45:23 -05001018 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001019
chaviw9eaa22c2020-07-01 16:21:27 -07001020 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1021 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1022 }
1023
1024 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001025
yunho.shinf4a80b82020-11-16 21:13:57 +09001026 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1027
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001028 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1029 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1030 expectedFlags);
1031 }
1032
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1034 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1035 }
1036
Svet Ganov5d3bc372020-01-26 23:11:07 -08001037 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001038 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001039 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1040 expectedFlags);
1041 }
1042
1043 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001044 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001045 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1046 expectedFlags);
1047 }
1048
1049 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001050 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001051 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1052 }
1053
1054 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1055 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001056 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1057 expectedFlags);
1058 }
1059
Svet Ganov5d3bc372020-01-26 23:11:07 -08001060 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001061 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1062 int32_t expectedFlags = 0) {
1063 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1064 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001065 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1066 }
1067
1068 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001069 int32_t expectedFlags = 0) {
1070 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1071 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001072 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1073 }
1074
1075 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001076 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001077 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1078 expectedFlags);
1079 }
1080
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001081 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1082 int32_t expectedFlags = 0) {
1083 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1084 expectedFlags);
1085 }
1086
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001087 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1088 ASSERT_NE(mInputReceiver, nullptr)
1089 << "Cannot consume events from a window with no receiver";
1090 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1091 }
1092
Prabir Pradhan99987712020-11-10 18:43:05 -08001093 void consumeCaptureEvent(bool hasCapture) {
1094 ASSERT_NE(mInputReceiver, nullptr)
1095 << "Cannot consume events from a window with no receiver";
1096 mInputReceiver->consumeCaptureEvent(hasCapture);
1097 }
1098
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001099 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1100 std::optional<int32_t> expectedDisplayId,
1101 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001102 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1103 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1104 expectedFlags);
1105 }
1106
arthurhungb89ccb02020-12-30 16:19:01 +08001107 void consumeDragEvent(bool isExiting, float x, float y) {
1108 mInputReceiver->consumeDragEvent(isExiting, x, y);
1109 }
1110
Antonio Kantekf16f2832021-09-28 04:39:20 +00001111 void consumeTouchModeEvent(bool inTouchMode) {
1112 ASSERT_NE(mInputReceiver, nullptr)
1113 << "Cannot consume events from a window with no receiver";
1114 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1115 }
1116
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001117 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001118 if (mInputReceiver == nullptr) {
1119 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1120 return std::nullopt;
1121 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001122 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001123 }
1124
1125 void finishEvent(uint32_t sequenceNum) {
1126 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1127 mInputReceiver->finishEvent(sequenceNum);
1128 }
1129
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001130 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1131 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1132 mInputReceiver->sendTimeline(inputEventId, timeline);
1133 }
1134
chaviwaf87b3e2019-10-01 16:59:28 -07001135 InputEvent* consume() {
1136 if (mInputReceiver == nullptr) {
1137 return nullptr;
1138 }
1139 return mInputReceiver->consume();
1140 }
1141
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001142 MotionEvent* consumeMotion() {
1143 InputEvent* event = consume();
1144 if (event == nullptr) {
1145 ADD_FAILURE() << "Consume failed : no event";
1146 return nullptr;
1147 }
1148 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1149 ADD_FAILURE() << "Instead of motion event, got "
1150 << inputEventTypeToString(event->getType());
1151 return nullptr;
1152 }
1153 return static_cast<MotionEvent*>(event);
1154 }
1155
Arthur Hungb92218b2018-08-14 12:00:21 +08001156 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001157 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001158 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001159 return; // Can't receive events if the window does not have input channel
1160 }
1161 ASSERT_NE(nullptr, mInputReceiver)
1162 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001163 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001164 }
1165
chaviwaf87b3e2019-10-01 16:59:28 -07001166 sp<IBinder> getToken() { return mInfo.token; }
1167
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001168 const std::string& getName() { return mName; }
1169
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001170 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1171 mInfo.ownerPid = ownerPid;
1172 mInfo.ownerUid = ownerUid;
1173 }
1174
chaviwd1c23182019-12-20 18:44:56 -08001175private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001176 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001177 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001178 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001179};
1180
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001181std::atomic<int32_t> FakeWindowHandle::sId{1};
1182
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001183static InputEventInjectionResult injectKey(
1184 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1185 int32_t displayId = ADISPLAY_ID_NONE,
1186 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001187 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1188 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001189 KeyEvent event;
1190 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1191
1192 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001193 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001194 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1195 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001196
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001197 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1198 if (!allowKeyRepeat) {
1199 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1200 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001201 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001202 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001203 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001204}
1205
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001206static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1207 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001208 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1209}
1210
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001211// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1212// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1213// has to be woken up to process the repeating key.
1214static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1215 int32_t displayId = ADISPLAY_ID_NONE) {
1216 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1217 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1218 /* allowKeyRepeat */ false);
1219}
1220
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001221static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1222 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001223 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1224}
1225
Garfield Tandf26e862020-07-01 20:18:19 -07001226class PointerBuilder {
1227public:
1228 PointerBuilder(int32_t id, int32_t toolType) {
1229 mProperties.clear();
1230 mProperties.id = id;
1231 mProperties.toolType = toolType;
1232 mCoords.clear();
1233 }
1234
1235 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1236
1237 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1238
1239 PointerBuilder& axis(int32_t axis, float value) {
1240 mCoords.setAxisValue(axis, value);
1241 return *this;
1242 }
1243
1244 PointerProperties buildProperties() const { return mProperties; }
1245
1246 PointerCoords buildCoords() const { return mCoords; }
1247
1248private:
1249 PointerProperties mProperties;
1250 PointerCoords mCoords;
1251};
1252
1253class MotionEventBuilder {
1254public:
1255 MotionEventBuilder(int32_t action, int32_t source) {
1256 mAction = action;
1257 mSource = source;
1258 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1259 }
1260
1261 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1262 mEventTime = eventTime;
1263 return *this;
1264 }
1265
1266 MotionEventBuilder& displayId(int32_t displayId) {
1267 mDisplayId = displayId;
1268 return *this;
1269 }
1270
1271 MotionEventBuilder& actionButton(int32_t actionButton) {
1272 mActionButton = actionButton;
1273 return *this;
1274 }
1275
arthurhung6d4bed92021-03-17 11:59:33 +08001276 MotionEventBuilder& buttonState(int32_t buttonState) {
1277 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001278 return *this;
1279 }
1280
1281 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1282 mRawXCursorPosition = rawXCursorPosition;
1283 return *this;
1284 }
1285
1286 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1287 mRawYCursorPosition = rawYCursorPosition;
1288 return *this;
1289 }
1290
1291 MotionEventBuilder& pointer(PointerBuilder pointer) {
1292 mPointers.push_back(pointer);
1293 return *this;
1294 }
1295
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001296 MotionEventBuilder& addFlag(uint32_t flags) {
1297 mFlags |= flags;
1298 return *this;
1299 }
1300
Garfield Tandf26e862020-07-01 20:18:19 -07001301 MotionEvent build() {
1302 std::vector<PointerProperties> pointerProperties;
1303 std::vector<PointerCoords> pointerCoords;
1304 for (const PointerBuilder& pointer : mPointers) {
1305 pointerProperties.push_back(pointer.buildProperties());
1306 pointerCoords.push_back(pointer.buildCoords());
1307 }
1308
1309 // Set mouse cursor position for the most common cases to avoid boilerplate.
1310 if (mSource == AINPUT_SOURCE_MOUSE &&
1311 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1312 mPointers.size() == 1) {
1313 mRawXCursorPosition = pointerCoords[0].getX();
1314 mRawYCursorPosition = pointerCoords[0].getY();
1315 }
1316
1317 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001318 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001319 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001320 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001321 mButtonState, MotionClassification::NONE, identityTransform,
1322 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001323 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1324 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001325
1326 return event;
1327 }
1328
1329private:
1330 int32_t mAction;
1331 int32_t mSource;
1332 nsecs_t mEventTime;
1333 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1334 int32_t mActionButton{0};
1335 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001336 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001337 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1338 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1339
1340 std::vector<PointerBuilder> mPointers;
1341};
1342
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001343static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001344 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1345 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001346 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001347 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1348 injectionTimeout,
1349 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1350}
1351
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001352static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001353 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1354 const PointF& position,
1355 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001356 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1357 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001358 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001359 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001360 MotionEvent event = MotionEventBuilder(action, source)
1361 .displayId(displayId)
1362 .eventTime(eventTime)
1363 .rawXCursorPosition(cursorPosition.x)
1364 .rawYCursorPosition(cursorPosition.y)
1365 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1366 .x(position.x)
1367 .y(position.y))
1368 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001369
1370 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001371 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001372}
1373
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001374static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1375 int32_t source, int32_t displayId,
1376 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001377 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001378}
1379
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001380static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1381 int32_t source, int32_t displayId,
1382 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001383 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001384}
1385
Jackal Guof9696682018-10-05 12:23:23 +08001386static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1387 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1388 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001389 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1390 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1391 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001392
1393 return args;
1394}
1395
chaviwd1c23182019-12-20 18:44:56 -08001396static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1397 const std::vector<PointF>& points) {
1398 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001399 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1400 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1401 }
1402
chaviwd1c23182019-12-20 18:44:56 -08001403 PointerProperties pointerProperties[pointerCount];
1404 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001405
chaviwd1c23182019-12-20 18:44:56 -08001406 for (size_t i = 0; i < pointerCount; i++) {
1407 pointerProperties[i].clear();
1408 pointerProperties[i].id = i;
1409 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001410
chaviwd1c23182019-12-20 18:44:56 -08001411 pointerCoords[i].clear();
1412 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1413 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1414 }
Jackal Guof9696682018-10-05 12:23:23 +08001415
1416 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1417 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001418 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001419 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1420 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001421 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1422 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001423 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1424 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001425
1426 return args;
1427}
1428
chaviwd1c23182019-12-20 18:44:56 -08001429static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1430 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1431}
1432
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001433static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1434 const PointerCaptureRequest& request) {
1435 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001436}
1437
Arthur Hungb92218b2018-08-14 12:00:21 +08001438TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001439 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001440 sp<FakeWindowHandle> window =
1441 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001442
Arthur Hung72d8dc32020-03-28 00:48:39 +00001443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1445 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1446 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001447
1448 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001449 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001450}
1451
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001452/**
1453 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1454 * To ensure that window receives only events that were directly inside of it, add
1455 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1456 * when finding touched windows.
1457 * This test serves as a sanity check for the next test, where setInputWindows is
1458 * called twice.
1459 */
1460TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001461 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001462 sp<FakeWindowHandle> window =
1463 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1464 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001465 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001466
1467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1470 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001471 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001472
1473 // Window should receive motion event.
1474 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1475}
1476
1477/**
1478 * Calling setInputWindows twice, with the same info, should not cause any issues.
1479 * To ensure that window receives only events that were directly inside of it, add
1480 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1481 * when finding touched windows.
1482 */
1483TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001484 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001485 sp<FakeWindowHandle> window =
1486 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1487 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001488 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001489
1490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1491 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001493 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1494 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001495 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001496
1497 // Window should receive motion event.
1498 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1499}
1500
Arthur Hungb92218b2018-08-14 12:00:21 +08001501// The foreground window should receive the first touch down event.
1502TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001504 sp<FakeWindowHandle> windowTop =
1505 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1506 sp<FakeWindowHandle> windowSecond =
1507 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001508
Arthur Hung72d8dc32020-03-28 00:48:39 +00001509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1511 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1512 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001513
1514 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001515 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001516 windowSecond->assertNoEvents();
1517}
1518
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001519/**
1520 * Two windows: A top window, and a wallpaper behind the window.
1521 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1522 * gets ACTION_CANCEL.
1523 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1524 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1525 */
1526TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1527 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1528 sp<FakeWindowHandle> foregroundWindow =
1529 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1530 foregroundWindow->setHasWallpaper(true);
1531 sp<FakeWindowHandle> wallpaperWindow =
1532 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1533 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1534 constexpr int expectedWallpaperFlags =
1535 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1536
1537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1540 {100, 200}))
1541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1542
1543 // Both foreground window and its wallpaper should receive the touch down
1544 foregroundWindow->consumeMotionDown();
1545 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1546
1547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1548 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1549 ADISPLAY_ID_DEFAULT, {110, 200}))
1550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1551
1552 foregroundWindow->consumeMotionMove();
1553 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1554
1555 // Now the foreground window goes away, but the wallpaper stays
1556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1557 foregroundWindow->consumeMotionCancel();
1558 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1559 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1560}
1561
1562/**
1563 * A single window that receives touch (on top), and a wallpaper window underneath it.
1564 * The top window gets a multitouch gesture.
1565 * Ensure that wallpaper gets the same gesture.
1566 */
1567TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1568 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1569 sp<FakeWindowHandle> window =
1570 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1571 window->setHasWallpaper(true);
1572
1573 sp<FakeWindowHandle> wallpaperWindow =
1574 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1575 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1576 constexpr int expectedWallpaperFlags =
1577 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1578
1579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1580
1581 // Touch down on top window
1582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1584 {100, 100}))
1585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1586
1587 // Both top window and its wallpaper should receive the touch down
1588 window->consumeMotionDown();
1589 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1590
1591 // Second finger down on the top window
1592 const MotionEvent secondFingerDownEvent =
1593 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1594 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1595 AINPUT_SOURCE_TOUCHSCREEN)
1596 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1597 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1598 .x(100)
1599 .y(100))
1600 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1601 .x(150)
1602 .y(150))
1603 .build();
1604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1605 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1606 InputEventInjectionSync::WAIT_FOR_RESULT))
1607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1608
1609 window->consumeMotionPointerDown(1 /* pointerIndex */);
1610 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1611 expectedWallpaperFlags);
1612 window->assertNoEvents();
1613 wallpaperWindow->assertNoEvents();
1614}
1615
1616/**
1617 * Two windows: a window on the left and window on the right.
1618 * A third window, wallpaper, is behind both windows, and spans both top windows.
1619 * The first touch down goes to the left window. A second pointer touches down on the right window.
1620 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1621 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1622 * ACTION_POINTER_DOWN(1).
1623 */
1624TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1625 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1626 sp<FakeWindowHandle> leftWindow =
1627 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1628 leftWindow->setFrame(Rect(0, 0, 200, 200));
1629 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1630 leftWindow->setHasWallpaper(true);
1631
1632 sp<FakeWindowHandle> rightWindow =
1633 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1634 rightWindow->setFrame(Rect(200, 0, 400, 200));
1635 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1636 rightWindow->setHasWallpaper(true);
1637
1638 sp<FakeWindowHandle> wallpaperWindow =
1639 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1640 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1641 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1642 constexpr int expectedWallpaperFlags =
1643 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1644
1645 mDispatcher->setInputWindows(
1646 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1647
1648 // Touch down on left window
1649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1650 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1651 {100, 100}))
1652 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1653
1654 // Both foreground window and its wallpaper should receive the touch down
1655 leftWindow->consumeMotionDown();
1656 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1657
1658 // Second finger down on the right window
1659 const MotionEvent secondFingerDownEvent =
1660 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1661 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1662 AINPUT_SOURCE_TOUCHSCREEN)
1663 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1664 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1665 .x(100)
1666 .y(100))
1667 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1668 .x(300)
1669 .y(100))
1670 .build();
1671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1672 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1673 InputEventInjectionSync::WAIT_FOR_RESULT))
1674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1675
1676 leftWindow->consumeMotionMove();
1677 // Since the touch is split, right window gets ACTION_DOWN
1678 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1679 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1680 expectedWallpaperFlags);
1681
1682 // Now, leftWindow, which received the first finger, disappears.
1683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1684 leftWindow->consumeMotionCancel();
1685 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1686 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1687
1688 // The pointer that's still down on the right window moves, and goes to the right window only.
1689 // As far as the dispatcher's concerned though, both pointers are still present.
1690 const MotionEvent secondFingerMoveEvent =
1691 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1692 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1693 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1694 .x(100)
1695 .y(100))
1696 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1697 .x(310)
1698 .y(110))
1699 .build();
1700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1701 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1702 InputEventInjectionSync::WAIT_FOR_RESULT));
1703 rightWindow->consumeMotionMove();
1704
1705 leftWindow->assertNoEvents();
1706 rightWindow->assertNoEvents();
1707 wallpaperWindow->assertNoEvents();
1708}
1709
Garfield Tandf26e862020-07-01 20:18:19 -07001710TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001712 sp<FakeWindowHandle> windowLeft =
1713 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1714 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001715 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001716 sp<FakeWindowHandle> windowRight =
1717 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1718 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001719 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001720
1721 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1722
1723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1724
1725 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001727 injectMotionEvent(mDispatcher,
1728 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1729 AINPUT_SOURCE_MOUSE)
1730 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1731 .x(900)
1732 .y(400))
1733 .build()));
1734 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1735 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1736 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1737 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1738
1739 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001741 injectMotionEvent(mDispatcher,
1742 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1743 AINPUT_SOURCE_MOUSE)
1744 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1745 .x(300)
1746 .y(400))
1747 .build()));
1748 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1749 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1750 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1751 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1752 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1753 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1754
1755 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001757 injectMotionEvent(mDispatcher,
1758 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1759 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1760 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1761 .x(300)
1762 .y(400))
1763 .build()));
1764 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1765
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001767 injectMotionEvent(mDispatcher,
1768 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1769 AINPUT_SOURCE_MOUSE)
1770 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1771 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1772 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1773 .x(300)
1774 .y(400))
1775 .build()));
1776 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1777 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1778
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001780 injectMotionEvent(mDispatcher,
1781 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1782 AINPUT_SOURCE_MOUSE)
1783 .buttonState(0)
1784 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1785 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1786 .x(300)
1787 .y(400))
1788 .build()));
1789 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1790 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1791
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001793 injectMotionEvent(mDispatcher,
1794 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1795 .buttonState(0)
1796 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1797 .x(300)
1798 .y(400))
1799 .build()));
1800 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1801
1802 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001803 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001804 injectMotionEvent(mDispatcher,
1805 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1806 AINPUT_SOURCE_MOUSE)
1807 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1808 .x(900)
1809 .y(400))
1810 .build()));
1811 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1812 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1813 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1814 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1815 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1816 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1817}
1818
1819// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1820// directly in this test.
1821TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001823 sp<FakeWindowHandle> window =
1824 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1825 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001826 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001827
1828 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1829
1830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1831
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001833 injectMotionEvent(mDispatcher,
1834 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1835 AINPUT_SOURCE_MOUSE)
1836 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1837 .x(300)
1838 .y(400))
1839 .build()));
1840 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1841 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1842
1843 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001845 injectMotionEvent(mDispatcher,
1846 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1847 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1848 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1849 .x(300)
1850 .y(400))
1851 .build()));
1852 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1853
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001855 injectMotionEvent(mDispatcher,
1856 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1857 AINPUT_SOURCE_MOUSE)
1858 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1859 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1860 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1861 .x(300)
1862 .y(400))
1863 .build()));
1864 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1865 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1866
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001867 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001868 injectMotionEvent(mDispatcher,
1869 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1870 AINPUT_SOURCE_MOUSE)
1871 .buttonState(0)
1872 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1873 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1874 .x(300)
1875 .y(400))
1876 .build()));
1877 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1878 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001881 injectMotionEvent(mDispatcher,
1882 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1883 .buttonState(0)
1884 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1885 .x(300)
1886 .y(400))
1887 .build()));
1888 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1889
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001891 injectMotionEvent(mDispatcher,
1892 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1893 AINPUT_SOURCE_MOUSE)
1894 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1895 .x(300)
1896 .y(400))
1897 .build()));
1898 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1899 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1900}
1901
Garfield Tan00f511d2019-06-12 16:55:40 -07001902TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001903 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001904
1905 sp<FakeWindowHandle> windowLeft =
1906 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1907 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001908 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001909 sp<FakeWindowHandle> windowRight =
1910 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1911 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001912 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001913
1914 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1915
Arthur Hung72d8dc32020-03-28 00:48:39 +00001916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001917
1918 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1919 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001921 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001922 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001923 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001924 windowRight->assertNoEvents();
1925}
1926
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001927TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001928 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001929 sp<FakeWindowHandle> window =
1930 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001931 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001932
Arthur Hung72d8dc32020-03-28 00:48:39 +00001933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001934 setFocusedWindow(window);
1935
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001936 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001937
1938 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1939 mDispatcher->notifyKey(&keyArgs);
1940
1941 // Window should receive key down event.
1942 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1943
1944 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1945 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001946 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001947 mDispatcher->notifyDeviceReset(&args);
1948 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1949 AKEY_EVENT_FLAG_CANCELED);
1950}
1951
1952TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001953 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001954 sp<FakeWindowHandle> window =
1955 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1956
Arthur Hung72d8dc32020-03-28 00:48:39 +00001957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001958
1959 NotifyMotionArgs motionArgs =
1960 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1961 ADISPLAY_ID_DEFAULT);
1962 mDispatcher->notifyMotion(&motionArgs);
1963
1964 // Window should receive motion down event.
1965 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1966
1967 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1968 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001969 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001970 mDispatcher->notifyDeviceReset(&args);
1971 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1972 0 /*expectedFlags*/);
1973}
1974
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001975using TransferFunction =
1976 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1977
1978class TransferTouchFixture : public InputDispatcherTest,
1979 public ::testing::WithParamInterface<TransferFunction> {};
1980
1981TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001982 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001983
1984 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001985 sp<FakeWindowHandle> firstWindow =
1986 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1987 sp<FakeWindowHandle> secondWindow =
1988 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001989
1990 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001992
1993 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001994 NotifyMotionArgs downMotionArgs =
1995 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1996 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001997 mDispatcher->notifyMotion(&downMotionArgs);
1998 // Only the first window should get the down event
1999 firstWindow->consumeMotionDown();
2000 secondWindow->assertNoEvents();
2001
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002002 // Transfer touch to the second window
2003 TransferFunction f = GetParam();
2004 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2005 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002006 // The first window gets cancel and the second gets down
2007 firstWindow->consumeMotionCancel();
2008 secondWindow->consumeMotionDown();
2009
2010 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002011 NotifyMotionArgs upMotionArgs =
2012 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2013 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002014 mDispatcher->notifyMotion(&upMotionArgs);
2015 // The first window gets no events and the second gets up
2016 firstWindow->assertNoEvents();
2017 secondWindow->consumeMotionUp();
2018}
2019
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002020TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002021 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002022
2023 PointF touchPoint = {10, 10};
2024
2025 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002026 sp<FakeWindowHandle> firstWindow =
2027 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2028 sp<FakeWindowHandle> secondWindow =
2029 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002030
2031 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002033
2034 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002035 NotifyMotionArgs downMotionArgs =
2036 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2037 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002038 mDispatcher->notifyMotion(&downMotionArgs);
2039 // Only the first window should get the down event
2040 firstWindow->consumeMotionDown();
2041 secondWindow->assertNoEvents();
2042
2043 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002044 NotifyMotionArgs pointerDownMotionArgs =
2045 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2046 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2047 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2048 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002049 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2050 // Only the first window should get the pointer down event
2051 firstWindow->consumeMotionPointerDown(1);
2052 secondWindow->assertNoEvents();
2053
2054 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002055 TransferFunction f = GetParam();
2056 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2057 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002058 // The first window gets cancel and the second gets down and pointer down
2059 firstWindow->consumeMotionCancel();
2060 secondWindow->consumeMotionDown();
2061 secondWindow->consumeMotionPointerDown(1);
2062
2063 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002064 NotifyMotionArgs pointerUpMotionArgs =
2065 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2066 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2067 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2068 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002069 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2070 // The first window gets nothing and the second gets pointer up
2071 firstWindow->assertNoEvents();
2072 secondWindow->consumeMotionPointerUp(1);
2073
2074 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002075 NotifyMotionArgs upMotionArgs =
2076 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2077 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002078 mDispatcher->notifyMotion(&upMotionArgs);
2079 // The first window gets nothing and the second gets up
2080 firstWindow->assertNoEvents();
2081 secondWindow->consumeMotionUp();
2082}
2083
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002084// For the cases of single pointer touch and two pointers non-split touch, the api's
2085// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2086// for the case where there are multiple pointers split across several windows.
2087INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2088 ::testing::Values(
2089 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
2090 sp<IBinder> destChannelToken) {
2091 return dispatcher->transferTouch(destChannelToken);
2092 },
2093 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
2094 sp<IBinder> to) {
2095 return dispatcher->transferTouchFocus(from, to,
2096 false /*isDragAndDrop*/);
2097 }));
2098
Svet Ganov5d3bc372020-01-26 23:11:07 -08002099TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002100 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002101
2102 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002103 sp<FakeWindowHandle> firstWindow =
2104 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002105 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002106 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002107
2108 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002109 sp<FakeWindowHandle> secondWindow =
2110 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002111 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002112 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002113
2114 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002116
2117 PointF pointInFirst = {300, 200};
2118 PointF pointInSecond = {300, 600};
2119
2120 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002121 NotifyMotionArgs firstDownMotionArgs =
2122 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2123 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002124 mDispatcher->notifyMotion(&firstDownMotionArgs);
2125 // Only the first window should get the down event
2126 firstWindow->consumeMotionDown();
2127 secondWindow->assertNoEvents();
2128
2129 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002130 NotifyMotionArgs secondDownMotionArgs =
2131 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2132 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2133 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2134 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002135 mDispatcher->notifyMotion(&secondDownMotionArgs);
2136 // The first window gets a move and the second a down
2137 firstWindow->consumeMotionMove();
2138 secondWindow->consumeMotionDown();
2139
2140 // Transfer touch focus to the second window
2141 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2142 // The first window gets cancel and the new gets pointer down (it already saw down)
2143 firstWindow->consumeMotionCancel();
2144 secondWindow->consumeMotionPointerDown(1);
2145
2146 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002147 NotifyMotionArgs pointerUpMotionArgs =
2148 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2149 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2150 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2151 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002152 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2153 // The first window gets nothing and the second gets pointer up
2154 firstWindow->assertNoEvents();
2155 secondWindow->consumeMotionPointerUp(1);
2156
2157 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002158 NotifyMotionArgs upMotionArgs =
2159 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2160 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002161 mDispatcher->notifyMotion(&upMotionArgs);
2162 // The first window gets nothing and the second gets up
2163 firstWindow->assertNoEvents();
2164 secondWindow->consumeMotionUp();
2165}
2166
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002167// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2168// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2169// touch is not supported, so the touch should continue on those windows and the transferred-to
2170// window should get nothing.
2171TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2172 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2173
2174 // Create a non touch modal window that supports split touch
2175 sp<FakeWindowHandle> firstWindow =
2176 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2177 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002178 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002179
2180 // Create a non touch modal window that supports split touch
2181 sp<FakeWindowHandle> secondWindow =
2182 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2183 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002184 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002185
2186 // Add the windows to the dispatcher
2187 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2188
2189 PointF pointInFirst = {300, 200};
2190 PointF pointInSecond = {300, 600};
2191
2192 // Send down to the first window
2193 NotifyMotionArgs firstDownMotionArgs =
2194 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2195 ADISPLAY_ID_DEFAULT, {pointInFirst});
2196 mDispatcher->notifyMotion(&firstDownMotionArgs);
2197 // Only the first window should get the down event
2198 firstWindow->consumeMotionDown();
2199 secondWindow->assertNoEvents();
2200
2201 // Send down to the second window
2202 NotifyMotionArgs secondDownMotionArgs =
2203 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2204 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2205 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2206 {pointInFirst, pointInSecond});
2207 mDispatcher->notifyMotion(&secondDownMotionArgs);
2208 // The first window gets a move and the second a down
2209 firstWindow->consumeMotionMove();
2210 secondWindow->consumeMotionDown();
2211
2212 // Transfer touch focus to the second window
2213 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2214 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2215 ASSERT_FALSE(transferred);
2216 firstWindow->assertNoEvents();
2217 secondWindow->assertNoEvents();
2218
2219 // The rest of the dispatch should proceed as normal
2220 // Send pointer up to the second window
2221 NotifyMotionArgs pointerUpMotionArgs =
2222 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2223 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2224 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2225 {pointInFirst, pointInSecond});
2226 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2227 // The first window gets MOVE and the second gets pointer up
2228 firstWindow->consumeMotionMove();
2229 secondWindow->consumeMotionUp();
2230
2231 // Send up event to the first window
2232 NotifyMotionArgs upMotionArgs =
2233 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2234 ADISPLAY_ID_DEFAULT);
2235 mDispatcher->notifyMotion(&upMotionArgs);
2236 // The first window gets nothing and the second gets up
2237 firstWindow->consumeMotionUp();
2238 secondWindow->assertNoEvents();
2239}
2240
Arthur Hungabbb9d82021-09-01 14:52:30 +00002241// This case will create two windows and one mirrored window on the default display and mirror
2242// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2243// the windows info of second display before default display.
2244TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2246 sp<FakeWindowHandle> firstWindowInPrimary =
2247 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2248 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2249 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2250 sp<FakeWindowHandle> secondWindowInPrimary =
2251 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2252 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2253 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2254
2255 sp<FakeWindowHandle> mirrorWindowInPrimary =
2256 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2257 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2258 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2259
2260 sp<FakeWindowHandle> firstWindowInSecondary =
2261 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2262 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2263 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2264
2265 sp<FakeWindowHandle> secondWindowInSecondary =
2266 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2267 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2268 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2269
2270 // Update window info, let it find window handle of second display first.
2271 mDispatcher->setInputWindows(
2272 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2273 {ADISPLAY_ID_DEFAULT,
2274 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2275
2276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2277 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2278 {50, 50}))
2279 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2280
2281 // Window should receive motion event.
2282 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2283
2284 // Transfer touch focus
2285 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2286 secondWindowInPrimary->getToken()));
2287 // The first window gets cancel.
2288 firstWindowInPrimary->consumeMotionCancel();
2289 secondWindowInPrimary->consumeMotionDown();
2290
2291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2292 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2293 ADISPLAY_ID_DEFAULT, {150, 50}))
2294 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2295 firstWindowInPrimary->assertNoEvents();
2296 secondWindowInPrimary->consumeMotionMove();
2297
2298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2299 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2300 {150, 50}))
2301 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2302 firstWindowInPrimary->assertNoEvents();
2303 secondWindowInPrimary->consumeMotionUp();
2304}
2305
2306// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2307// 'transferTouch' api.
2308TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2310 sp<FakeWindowHandle> firstWindowInPrimary =
2311 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2312 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2313 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2314 sp<FakeWindowHandle> secondWindowInPrimary =
2315 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2316 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2317 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2318
2319 sp<FakeWindowHandle> mirrorWindowInPrimary =
2320 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2321 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2322 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2323
2324 sp<FakeWindowHandle> firstWindowInSecondary =
2325 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2326 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2327 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2328
2329 sp<FakeWindowHandle> secondWindowInSecondary =
2330 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2331 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2332 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2333
2334 // Update window info, let it find window handle of second display first.
2335 mDispatcher->setInputWindows(
2336 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2337 {ADISPLAY_ID_DEFAULT,
2338 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2339
2340 // Touch on second display.
2341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2343 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2344
2345 // Window should receive motion event.
2346 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2347
2348 // Transfer touch focus
2349 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2350
2351 // The first window gets cancel.
2352 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2353 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2354
2355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2356 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2357 SECOND_DISPLAY_ID, {150, 50}))
2358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2359 firstWindowInPrimary->assertNoEvents();
2360 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2361
2362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2363 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2364 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2365 firstWindowInPrimary->assertNoEvents();
2366 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2367}
2368
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002369TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002371 sp<FakeWindowHandle> window =
2372 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2373
Vishnu Nair47074b82020-08-14 11:54:47 -07002374 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002376 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002377
2378 window->consumeFocusEvent(true);
2379
2380 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2381 mDispatcher->notifyKey(&keyArgs);
2382
2383 // Window should receive key down event.
2384 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2385}
2386
2387TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002388 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002389 sp<FakeWindowHandle> window =
2390 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2391
Arthur Hung72d8dc32020-03-28 00:48:39 +00002392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002393
2394 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2395 mDispatcher->notifyKey(&keyArgs);
2396 mDispatcher->waitForIdle();
2397
2398 window->assertNoEvents();
2399}
2400
2401// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2402TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002404 sp<FakeWindowHandle> window =
2405 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2406
Arthur Hung72d8dc32020-03-28 00:48:39 +00002407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002408
2409 // Send key
2410 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2411 mDispatcher->notifyKey(&keyArgs);
2412 // Send motion
2413 NotifyMotionArgs motionArgs =
2414 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2415 ADISPLAY_ID_DEFAULT);
2416 mDispatcher->notifyMotion(&motionArgs);
2417
2418 // Window should receive only the motion event
2419 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2420 window->assertNoEvents(); // Key event or focus event will not be received
2421}
2422
arthurhungea3f4fc2020-12-21 23:18:53 +08002423TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2424 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2425
2426 // Create first non touch modal window that supports split touch
2427 sp<FakeWindowHandle> firstWindow =
2428 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2429 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002430 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002431
2432 // Create second non touch modal window that supports split touch
2433 sp<FakeWindowHandle> secondWindow =
2434 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2435 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002436 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002437
2438 // Add the windows to the dispatcher
2439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2440
2441 PointF pointInFirst = {300, 200};
2442 PointF pointInSecond = {300, 600};
2443
2444 // Send down to the first window
2445 NotifyMotionArgs firstDownMotionArgs =
2446 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2447 ADISPLAY_ID_DEFAULT, {pointInFirst});
2448 mDispatcher->notifyMotion(&firstDownMotionArgs);
2449 // Only the first window should get the down event
2450 firstWindow->consumeMotionDown();
2451 secondWindow->assertNoEvents();
2452
2453 // Send down to the second window
2454 NotifyMotionArgs secondDownMotionArgs =
2455 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2456 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2457 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2458 {pointInFirst, pointInSecond});
2459 mDispatcher->notifyMotion(&secondDownMotionArgs);
2460 // The first window gets a move and the second a down
2461 firstWindow->consumeMotionMove();
2462 secondWindow->consumeMotionDown();
2463
2464 // Send pointer cancel to the second window
2465 NotifyMotionArgs pointerUpMotionArgs =
2466 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2467 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2468 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2469 {pointInFirst, pointInSecond});
2470 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2471 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2472 // The first window gets move and the second gets cancel.
2473 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2474 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2475
2476 // Send up event.
2477 NotifyMotionArgs upMotionArgs =
2478 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2479 ADISPLAY_ID_DEFAULT);
2480 mDispatcher->notifyMotion(&upMotionArgs);
2481 // The first window gets up and the second gets nothing.
2482 firstWindow->consumeMotionUp();
2483 secondWindow->assertNoEvents();
2484}
2485
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002486TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2488
2489 sp<FakeWindowHandle> window =
2490 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2491 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2492 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2493 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2494 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2495
2496 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2497 window->assertNoEvents();
2498 mDispatcher->waitForIdle();
2499}
2500
chaviwd1c23182019-12-20 18:44:56 -08002501class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002502public:
2503 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002504 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002505 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002506 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002507 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002508 }
2509
chaviwd1c23182019-12-20 18:44:56 -08002510 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2511
2512 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2513 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2514 expectedDisplayId, expectedFlags);
2515 }
2516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002517 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2518
2519 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2520
chaviwd1c23182019-12-20 18:44:56 -08002521 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2522 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2523 expectedDisplayId, expectedFlags);
2524 }
2525
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002526 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2527 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2528 expectedDisplayId, expectedFlags);
2529 }
2530
chaviwd1c23182019-12-20 18:44:56 -08002531 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2532 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2533 expectedDisplayId, expectedFlags);
2534 }
2535
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002536 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2537 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2538 expectedDisplayId, expectedFlags);
2539 }
2540
Evan Rosky84f07f02021-04-16 10:42:42 -07002541 MotionEvent* consumeMotion() {
2542 InputEvent* event = mInputReceiver->consume();
2543 if (!event) {
2544 ADD_FAILURE() << "No event was produced";
2545 return nullptr;
2546 }
2547 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2548 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2549 return nullptr;
2550 }
2551 return static_cast<MotionEvent*>(event);
2552 }
2553
chaviwd1c23182019-12-20 18:44:56 -08002554 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2555
2556private:
2557 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002558};
2559
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002560/**
2561 * Two entities that receive touch: A window, and a global monitor.
2562 * The touch goes to the window, and then the window disappears.
2563 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2564 * for the monitor, as well.
2565 * 1. foregroundWindow
2566 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2567 */
2568TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2570 sp<FakeWindowHandle> window =
2571 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2572
2573 FakeMonitorReceiver monitor =
2574 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2575 false /*isGestureMonitor*/);
2576
2577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2579 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2580 {100, 200}))
2581 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2582
2583 // Both the foreground window and the global monitor should receive the touch down
2584 window->consumeMotionDown();
2585 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2586
2587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2588 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2589 ADISPLAY_ID_DEFAULT, {110, 200}))
2590 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2591
2592 window->consumeMotionMove();
2593 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2594
2595 // Now the foreground window goes away
2596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2597 window->consumeMotionCancel();
2598 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2599
2600 // If more events come in, there will be no more foreground window to send them to. This will
2601 // cause a cancel for the monitor, as well.
2602 ASSERT_EQ(InputEventInjectionResult::FAILED,
2603 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2604 ADISPLAY_ID_DEFAULT, {120, 200}))
2605 << "Injection should fail because the window was removed";
2606 window->assertNoEvents();
2607 // Global monitor now gets the cancel
2608 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2609}
2610
Michael Wright3a240c42019-12-10 20:53:41 +00002611// Tests for gesture monitors
2612TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002613 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002614 sp<FakeWindowHandle> window =
2615 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002617
chaviwd1c23182019-12-20 18:44:56 -08002618 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2619 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002620
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002622 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002624 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002625 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002626}
2627
2628TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002630 sp<FakeWindowHandle> window =
2631 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2632
2633 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002634 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002635
Arthur Hung72d8dc32020-03-28 00:48:39 +00002636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002637 setFocusedWindow(window);
2638
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002639 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002640
chaviwd1c23182019-12-20 18:44:56 -08002641 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2642 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002643
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2645 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002646 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002647 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002648}
2649
2650TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002651 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002652 sp<FakeWindowHandle> window =
2653 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002655
chaviwd1c23182019-12-20 18:44:56 -08002656 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2657 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002658
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002662 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002663 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002664
2665 window->releaseChannel();
2666
chaviwd1c23182019-12-20 18:44:56 -08002667 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002668
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002670 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002671 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002672 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002673}
2674
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002675TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2676 FakeMonitorReceiver monitor =
2677 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2678 true /*isGestureMonitor*/);
2679
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002681 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2682 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2683 ASSERT_TRUE(consumeSeq);
2684
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002685 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002686 monitor.finishEvent(*consumeSeq);
2687 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002688 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002689}
2690
Evan Rosky84f07f02021-04-16 10:42:42 -07002691// Tests for gesture monitors
2692TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2693 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2694 sp<FakeWindowHandle> window =
2695 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2697 window->setWindowOffset(20, 40);
2698 window->setWindowTransform(0, 1, -1, 0);
2699
2700 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2701 true /*isGestureMonitor*/);
2702
2703 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2704 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2705 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2706 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2707 MotionEvent* event = monitor.consumeMotion();
2708 // Even though window has transform, gesture monitor must not.
2709 ASSERT_EQ(ui::Transform(), event->getTransform());
2710}
2711
chaviw81e2bb92019-12-18 15:03:51 -08002712TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002713 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002714 sp<FakeWindowHandle> window =
2715 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2716
Arthur Hung72d8dc32020-03-28 00:48:39 +00002717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002718
2719 NotifyMotionArgs motionArgs =
2720 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2721 ADISPLAY_ID_DEFAULT);
2722
2723 mDispatcher->notifyMotion(&motionArgs);
2724 // Window should receive motion down event.
2725 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2726
2727 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002728 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002729 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2730 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2731 motionArgs.pointerCoords[0].getX() - 10);
2732
2733 mDispatcher->notifyMotion(&motionArgs);
2734 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2735 0 /*expectedFlags*/);
2736}
2737
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002738/**
2739 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2740 * the device default right away. In the test scenario, we check both the default value,
2741 * and the action of enabling / disabling.
2742 */
2743TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002745 sp<FakeWindowHandle> window =
2746 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2747
2748 // Set focused application.
2749 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002750 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002751
2752 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002754 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002755 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2756
2757 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002758 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002760 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2761
2762 SCOPED_TRACE("Disable touch mode");
2763 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002764 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002765 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002767 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002768 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2769
2770 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002771 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002773 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2774
2775 SCOPED_TRACE("Enable touch mode again");
2776 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002777 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002778 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002780 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002781 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2782
2783 window->assertNoEvents();
2784}
2785
Gang Wange9087892020-01-07 12:17:14 -05002786TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002787 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002788 sp<FakeWindowHandle> window =
2789 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2790
2791 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002792 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002793
Arthur Hung72d8dc32020-03-28 00:48:39 +00002794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002795 setFocusedWindow(window);
2796
Gang Wange9087892020-01-07 12:17:14 -05002797 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2798
2799 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2800 mDispatcher->notifyKey(&keyArgs);
2801
2802 InputEvent* event = window->consume();
2803 ASSERT_NE(event, nullptr);
2804
2805 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2806 ASSERT_NE(verified, nullptr);
2807 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2808
2809 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2810 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2811 ASSERT_EQ(keyArgs.source, verified->source);
2812 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2813
2814 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2815
2816 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2817 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002818 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2819 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2820 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2821 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2822 ASSERT_EQ(0, verifiedKey.repeatCount);
2823}
2824
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002825TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002826 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002827 sp<FakeWindowHandle> window =
2828 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2829
2830 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2831
Arthur Hung72d8dc32020-03-28 00:48:39 +00002832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002833
2834 NotifyMotionArgs motionArgs =
2835 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2836 ADISPLAY_ID_DEFAULT);
2837 mDispatcher->notifyMotion(&motionArgs);
2838
2839 InputEvent* event = window->consume();
2840 ASSERT_NE(event, nullptr);
2841
2842 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2843 ASSERT_NE(verified, nullptr);
2844 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2845
2846 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2847 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2848 EXPECT_EQ(motionArgs.source, verified->source);
2849 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2850
2851 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2852
2853 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2854 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2855 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2856 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2857 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2858 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2859 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2860}
2861
Prabir Pradhan664834b2021-05-20 16:00:42 -07002862TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002863 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2864 sp<FakeWindowHandle> window =
2865 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2866 const std::string name = window->getName();
2867
2868 // Window gets transformed by offset values.
2869 window->setWindowOffset(500.0f, 500.0f);
2870
2871 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2872 window->setFocusable(true);
2873
2874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2875
2876 // First, we set focused window so that focusedWindowHandle is not null.
2877 setFocusedWindow(window);
2878
2879 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2880 window->consumeFocusEvent(true);
2881
Prabir Pradhan664834b2021-05-20 16:00:42 -07002882 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2883 AMOTION_EVENT_ACTION_DOWN),
2884 std::pair(AINPUT_SOURCE_JOYSTICK,
2885 AMOTION_EVENT_ACTION_MOVE)};
2886 for (const auto& [source, action] : nonTransformedSources) {
2887 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08002888 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002889
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002890 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08002891 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09002892
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002893 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07002894 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08002895 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002896
Prabir Pradhanbd527712021-03-09 19:17:09 -08002897 float expectedX = motionArgs.pointerCoords[0].getX();
2898 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002899
Prabir Pradhanbd527712021-03-09 19:17:09 -08002900 // Ensure the axis values from the final motion event are not transformed.
2901 EXPECT_EQ(expectedX, motionEvent.getX(0))
2902 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2903 << motionEvent.getX(0);
2904 EXPECT_EQ(expectedY, motionEvent.getY(0))
2905 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2906 << motionEvent.getY(0);
2907 // Ensure the raw and transformed axis values for the motion event are the same.
2908 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2909 << "expected raw and transformed X-axis values to be equal";
2910 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2911 << "expected raw and transformed Y-axis values to be equal";
2912 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002913}
2914
chaviw09c8d2d2020-08-24 15:48:26 -07002915/**
2916 * Ensure that separate calls to sign the same data are generating the same key.
2917 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2918 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2919 * tests.
2920 */
2921TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2922 KeyEvent event = getTestKeyEvent();
2923 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2924
2925 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2926 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2927 ASSERT_EQ(hmac1, hmac2);
2928}
2929
2930/**
2931 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2932 */
2933TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2934 KeyEvent event = getTestKeyEvent();
2935 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2936 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2937
2938 verifiedEvent.deviceId += 1;
2939 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2940
2941 verifiedEvent.source += 1;
2942 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2943
2944 verifiedEvent.eventTimeNanos += 1;
2945 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2946
2947 verifiedEvent.displayId += 1;
2948 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2949
2950 verifiedEvent.action += 1;
2951 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2952
2953 verifiedEvent.downTimeNanos += 1;
2954 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2955
2956 verifiedEvent.flags += 1;
2957 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2958
2959 verifiedEvent.keyCode += 1;
2960 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2961
2962 verifiedEvent.scanCode += 1;
2963 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2964
2965 verifiedEvent.metaState += 1;
2966 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2967
2968 verifiedEvent.repeatCount += 1;
2969 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2970}
2971
Vishnu Nair958da932020-08-21 17:12:37 -07002972TEST_F(InputDispatcherTest, SetFocusedWindow) {
2973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2974 sp<FakeWindowHandle> windowTop =
2975 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2976 sp<FakeWindowHandle> windowSecond =
2977 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2978 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2979
2980 // Top window is also focusable but is not granted focus.
2981 windowTop->setFocusable(true);
2982 windowSecond->setFocusable(true);
2983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2984 setFocusedWindow(windowSecond);
2985
2986 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2988 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002989
2990 // Focused window should receive event.
2991 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2992 windowTop->assertNoEvents();
2993}
2994
2995TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2997 sp<FakeWindowHandle> window =
2998 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2999 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3000
3001 window->setFocusable(true);
3002 // Release channel for window is no longer valid.
3003 window->releaseChannel();
3004 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3005 setFocusedWindow(window);
3006
3007 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003008 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3009 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003010
3011 // window channel is invalid, so it should not receive any input event.
3012 window->assertNoEvents();
3013}
3014
3015TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3016 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3017 sp<FakeWindowHandle> window =
3018 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3019 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3020
3021 // Window is not focusable.
3022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3023 setFocusedWindow(window);
3024
3025 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003026 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3027 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003028
3029 // window is invalid, so it should not receive any input event.
3030 window->assertNoEvents();
3031}
3032
3033TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3034 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3035 sp<FakeWindowHandle> windowTop =
3036 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3037 sp<FakeWindowHandle> windowSecond =
3038 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3040
3041 windowTop->setFocusable(true);
3042 windowSecond->setFocusable(true);
3043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3044 setFocusedWindow(windowTop);
3045 windowTop->consumeFocusEvent(true);
3046
3047 setFocusedWindow(windowSecond, windowTop);
3048 windowSecond->consumeFocusEvent(true);
3049 windowTop->consumeFocusEvent(false);
3050
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3052 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003053
3054 // Focused window should receive event.
3055 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3056}
3057
3058TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3059 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3060 sp<FakeWindowHandle> windowTop =
3061 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3062 sp<FakeWindowHandle> windowSecond =
3063 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3064 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3065
3066 windowTop->setFocusable(true);
3067 windowSecond->setFocusable(true);
3068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3069 setFocusedWindow(windowSecond, windowTop);
3070
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003071 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3072 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003073
3074 // Event should be dropped.
3075 windowTop->assertNoEvents();
3076 windowSecond->assertNoEvents();
3077}
3078
3079TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3080 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3081 sp<FakeWindowHandle> window =
3082 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3083 sp<FakeWindowHandle> previousFocusedWindow =
3084 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3085 ADISPLAY_ID_DEFAULT);
3086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3087
3088 window->setFocusable(true);
3089 previousFocusedWindow->setFocusable(true);
3090 window->setVisible(false);
3091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3092 setFocusedWindow(previousFocusedWindow);
3093 previousFocusedWindow->consumeFocusEvent(true);
3094
3095 // Requesting focus on invisible window takes focus from currently focused window.
3096 setFocusedWindow(window);
3097 previousFocusedWindow->consumeFocusEvent(false);
3098
3099 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003101 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003102 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003103
3104 // Window does not get focus event or key down.
3105 window->assertNoEvents();
3106
3107 // Window becomes visible.
3108 window->setVisible(true);
3109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3110
3111 // Window receives focus event.
3112 window->consumeFocusEvent(true);
3113 // Focused window receives key down.
3114 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3115}
3116
Vishnu Nair599f1412021-06-21 10:39:58 -07003117TEST_F(InputDispatcherTest, DisplayRemoved) {
3118 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3119 sp<FakeWindowHandle> window =
3120 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3121 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3122
3123 // window is granted focus.
3124 window->setFocusable(true);
3125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3126 setFocusedWindow(window);
3127 window->consumeFocusEvent(true);
3128
3129 // When a display is removed window loses focus.
3130 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3131 window->consumeFocusEvent(false);
3132}
3133
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003134/**
3135 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3136 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3137 * of the 'slipperyEnterWindow'.
3138 *
3139 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3140 * a way so that the touched location is no longer covered by the top window.
3141 *
3142 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3143 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3144 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3145 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3146 * with ACTION_DOWN).
3147 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3148 * window moved itself away from the touched location and had Flag::SLIPPERY.
3149 *
3150 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3151 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3152 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3153 *
3154 * In this test, we ensure that the event received by the bottom window has
3155 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3156 */
3157TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3158 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3159 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3160
3161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3162 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3163
3164 sp<FakeWindowHandle> slipperyExitWindow =
3165 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003166 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003167 // Make sure this one overlaps the bottom window
3168 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3169 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3170 // one. Windows with the same owner are not considered to be occluding each other.
3171 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3172
3173 sp<FakeWindowHandle> slipperyEnterWindow =
3174 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3175 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3176
3177 mDispatcher->setInputWindows(
3178 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3179
3180 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3181 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3182 ADISPLAY_ID_DEFAULT, {{50, 50}});
3183 mDispatcher->notifyMotion(&args);
3184 slipperyExitWindow->consumeMotionDown();
3185 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3186 mDispatcher->setInputWindows(
3187 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3188
3189 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3190 ADISPLAY_ID_DEFAULT, {{51, 51}});
3191 mDispatcher->notifyMotion(&args);
3192
3193 slipperyExitWindow->consumeMotionCancel();
3194
3195 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3196 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3197}
3198
Garfield Tan1c7bc862020-01-28 13:24:04 -08003199class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3200protected:
3201 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3202 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3203
Chris Yea209fde2020-07-22 13:54:51 -07003204 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003205 sp<FakeWindowHandle> mWindow;
3206
3207 virtual void SetUp() override {
3208 mFakePolicy = new FakeInputDispatcherPolicy();
3209 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
3210 mDispatcher = new InputDispatcher(mFakePolicy);
3211 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3212 ASSERT_EQ(OK, mDispatcher->start());
3213
3214 setUpWindow();
3215 }
3216
3217 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003218 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003219 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3220
Vishnu Nair47074b82020-08-14 11:54:47 -07003221 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003223 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003224 mWindow->consumeFocusEvent(true);
3225 }
3226
Chris Ye2ad95392020-09-01 13:44:44 -07003227 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003228 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003229 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003230 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3231 mDispatcher->notifyKey(&keyArgs);
3232
3233 // Window should receive key down event.
3234 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3235 }
3236
3237 void expectKeyRepeatOnce(int32_t repeatCount) {
3238 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3239 InputEvent* repeatEvent = mWindow->consume();
3240 ASSERT_NE(nullptr, repeatEvent);
3241
3242 uint32_t eventType = repeatEvent->getType();
3243 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3244
3245 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3246 uint32_t eventAction = repeatKeyEvent->getAction();
3247 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3248 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3249 }
3250
Chris Ye2ad95392020-09-01 13:44:44 -07003251 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003252 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003253 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003254 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3255 mDispatcher->notifyKey(&keyArgs);
3256
3257 // Window should receive key down event.
3258 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3259 0 /*expectedFlags*/);
3260 }
3261};
3262
3263TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003264 sendAndConsumeKeyDown(1 /* deviceId */);
3265 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3266 expectKeyRepeatOnce(repeatCount);
3267 }
3268}
3269
3270TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3271 sendAndConsumeKeyDown(1 /* deviceId */);
3272 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3273 expectKeyRepeatOnce(repeatCount);
3274 }
3275 sendAndConsumeKeyDown(2 /* deviceId */);
3276 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003277 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3278 expectKeyRepeatOnce(repeatCount);
3279 }
3280}
3281
3282TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003283 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003284 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003285 sendAndConsumeKeyUp(1 /* deviceId */);
3286 mWindow->assertNoEvents();
3287}
3288
3289TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3290 sendAndConsumeKeyDown(1 /* deviceId */);
3291 expectKeyRepeatOnce(1 /*repeatCount*/);
3292 sendAndConsumeKeyDown(2 /* deviceId */);
3293 expectKeyRepeatOnce(1 /*repeatCount*/);
3294 // Stale key up from device 1.
3295 sendAndConsumeKeyUp(1 /* deviceId */);
3296 // Device 2 is still down, keep repeating
3297 expectKeyRepeatOnce(2 /*repeatCount*/);
3298 expectKeyRepeatOnce(3 /*repeatCount*/);
3299 // Device 2 key up
3300 sendAndConsumeKeyUp(2 /* deviceId */);
3301 mWindow->assertNoEvents();
3302}
3303
3304TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3305 sendAndConsumeKeyDown(1 /* deviceId */);
3306 expectKeyRepeatOnce(1 /*repeatCount*/);
3307 sendAndConsumeKeyDown(2 /* deviceId */);
3308 expectKeyRepeatOnce(1 /*repeatCount*/);
3309 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3310 sendAndConsumeKeyUp(2 /* deviceId */);
3311 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003312 mWindow->assertNoEvents();
3313}
3314
liushenxiang42232912021-05-21 20:24:09 +08003315TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3316 sendAndConsumeKeyDown(DEVICE_ID);
3317 expectKeyRepeatOnce(1 /*repeatCount*/);
3318 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3319 mDispatcher->notifyDeviceReset(&args);
3320 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3321 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3322 mWindow->assertNoEvents();
3323}
3324
Garfield Tan1c7bc862020-01-28 13:24:04 -08003325TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003326 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003327 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3328 InputEvent* repeatEvent = mWindow->consume();
3329 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3330 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3331 IdGenerator::getSource(repeatEvent->getId()));
3332 }
3333}
3334
3335TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003336 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003337
3338 std::unordered_set<int32_t> idSet;
3339 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3340 InputEvent* repeatEvent = mWindow->consume();
3341 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3342 int32_t id = repeatEvent->getId();
3343 EXPECT_EQ(idSet.end(), idSet.find(id));
3344 idSet.insert(id);
3345 }
3346}
3347
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003348/* Test InputDispatcher for MultiDisplay */
3349class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3350public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003351 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003352 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003353
Chris Yea209fde2020-07-22 13:54:51 -07003354 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003355 windowInPrimary =
3356 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003357
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003358 // Set focus window for primary display, but focused display would be second one.
3359 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003360 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003361 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003362 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003363 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003364
Chris Yea209fde2020-07-22 13:54:51 -07003365 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003366 windowInSecondary =
3367 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003368 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003369 // Set focus display to second one.
3370 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3371 // Set focus window for second display.
3372 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003373 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003374 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003375 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003376 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003377 }
3378
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003379 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003380 InputDispatcherTest::TearDown();
3381
Chris Yea209fde2020-07-22 13:54:51 -07003382 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003383 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003384 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003385 windowInSecondary.clear();
3386 }
3387
3388protected:
Chris Yea209fde2020-07-22 13:54:51 -07003389 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003390 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003391 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003392 sp<FakeWindowHandle> windowInSecondary;
3393};
3394
3395TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3396 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3398 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003400 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003401 windowInSecondary->assertNoEvents();
3402
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003403 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3405 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003407 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003408 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003409}
3410
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003411TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003412 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3414 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003415 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003416 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003417 windowInSecondary->assertNoEvents();
3418
3419 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003421 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003422 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003423 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003424
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003425 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003426 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003427
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003428 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003429 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3430 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003431
3432 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003433 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003434 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003435 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003436 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003437 windowInSecondary->assertNoEvents();
3438}
3439
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003440// Test per-display input monitors for motion event.
3441TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003442 FakeMonitorReceiver monitorInPrimary =
3443 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3444 FakeMonitorReceiver monitorInSecondary =
3445 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003446
3447 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003451 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003452 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003453 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003454 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003455
3456 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003460 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003461 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003462 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003463 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003464
3465 // Test inject a non-pointer motion event.
3466 // If specific a display, it will dispatch to the focused window of particular display,
3467 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3470 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003471 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003472 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003473 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003474 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003475}
3476
3477// Test per-display input monitors for key event.
3478TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003479 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003480 FakeMonitorReceiver monitorInPrimary =
3481 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3482 FakeMonitorReceiver monitorInSecondary =
3483 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003484
3485 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3487 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003488 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003489 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003490 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003491 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003492}
3493
Vishnu Nair958da932020-08-21 17:12:37 -07003494TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3495 sp<FakeWindowHandle> secondWindowInPrimary =
3496 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3497 secondWindowInPrimary->setFocusable(true);
3498 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3499 setFocusedWindow(secondWindowInPrimary);
3500 windowInPrimary->consumeFocusEvent(false);
3501 secondWindowInPrimary->consumeFocusEvent(true);
3502
3503 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3505 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003506 windowInPrimary->assertNoEvents();
3507 windowInSecondary->assertNoEvents();
3508 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3509}
3510
Jackal Guof9696682018-10-05 12:23:23 +08003511class InputFilterTest : public InputDispatcherTest {
3512protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003513 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3514 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003515 NotifyMotionArgs motionArgs;
3516
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003517 motionArgs =
3518 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003519 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003520 motionArgs =
3521 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003522 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003523 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003524 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003525 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3526 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003527 } else {
3528 mFakePolicy->assertFilterInputEventWasNotCalled();
3529 }
3530 }
3531
3532 void testNotifyKey(bool expectToBeFiltered) {
3533 NotifyKeyArgs keyArgs;
3534
3535 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3536 mDispatcher->notifyKey(&keyArgs);
3537 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3538 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003539 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003540
3541 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003542 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003543 } else {
3544 mFakePolicy->assertFilterInputEventWasNotCalled();
3545 }
3546 }
3547};
3548
3549// Test InputFilter for MotionEvent
3550TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3551 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3552 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3553 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3554
3555 // Enable InputFilter
3556 mDispatcher->setInputFilterEnabled(true);
3557 // Test touch on both primary and second display, and check if both events are filtered.
3558 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3559 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3560
3561 // Disable InputFilter
3562 mDispatcher->setInputFilterEnabled(false);
3563 // Test touch on both primary and second display, and check if both events aren't filtered.
3564 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3565 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3566}
3567
3568// Test InputFilter for KeyEvent
3569TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3570 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3571 testNotifyKey(/*expectToBeFiltered*/ false);
3572
3573 // Enable InputFilter
3574 mDispatcher->setInputFilterEnabled(true);
3575 // Send a key event, and check if it is filtered.
3576 testNotifyKey(/*expectToBeFiltered*/ true);
3577
3578 // Disable InputFilter
3579 mDispatcher->setInputFilterEnabled(false);
3580 // Send a key event, and check if it isn't filtered.
3581 testNotifyKey(/*expectToBeFiltered*/ false);
3582}
3583
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003584// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3585// logical display coordinate space.
3586TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3587 ui::Transform firstDisplayTransform;
3588 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3589 ui::Transform secondDisplayTransform;
3590 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3591
3592 std::vector<gui::DisplayInfo> displayInfos(2);
3593 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3594 displayInfos[0].transform = firstDisplayTransform;
3595 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3596 displayInfos[1].transform = secondDisplayTransform;
3597
3598 mDispatcher->onWindowInfosChanged({}, displayInfos);
3599
3600 // Enable InputFilter
3601 mDispatcher->setInputFilterEnabled(true);
3602
3603 // Ensure the correct transforms are used for the displays.
3604 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3605 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3606}
3607
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003608class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3609protected:
3610 virtual void SetUp() override {
3611 InputDispatcherTest::SetUp();
3612
3613 /**
3614 * We don't need to enable input filter to test the injected event policy, but we enabled it
3615 * here to make the tests more realistic, since this policy only matters when inputfilter is
3616 * on.
3617 */
3618 mDispatcher->setInputFilterEnabled(true);
3619
3620 std::shared_ptr<InputApplicationHandle> application =
3621 std::make_shared<FakeApplicationHandle>();
3622 mWindow =
3623 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3624
3625 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3626 mWindow->setFocusable(true);
3627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3628 setFocusedWindow(mWindow);
3629 mWindow->consumeFocusEvent(true);
3630 }
3631
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003632 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3633 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003634 KeyEvent event;
3635
3636 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3637 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3638 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3639 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3640 const int32_t additionalPolicyFlags =
3641 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3643 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3644 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3645 policyFlags | additionalPolicyFlags));
3646
3647 InputEvent* received = mWindow->consume();
3648 ASSERT_NE(nullptr, received);
3649 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003650 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3651 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3652 ASSERT_EQ(flags, keyEvent.getFlags());
3653 }
3654
3655 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3656 int32_t flags) {
3657 MotionEvent event;
3658 PointerProperties pointerProperties[1];
3659 PointerCoords pointerCoords[1];
3660 pointerProperties[0].clear();
3661 pointerProperties[0].id = 0;
3662 pointerCoords[0].clear();
3663 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3664 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3665
3666 ui::Transform identityTransform;
3667 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3668 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3669 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3670 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3671 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003672 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003673 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003674 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3675
3676 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3678 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3679 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3680 policyFlags | additionalPolicyFlags));
3681
3682 InputEvent* received = mWindow->consume();
3683 ASSERT_NE(nullptr, received);
3684 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3685 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3686 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3687 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003688 }
3689
3690private:
3691 sp<FakeWindowHandle> mWindow;
3692};
3693
3694TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003695 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3696 // filter. Without it, the event will no different from a regularly injected event, and the
3697 // injected device id will be overwritten.
3698 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3699 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003700}
3701
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003702TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003703 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003704 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3705 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3706}
3707
3708TEST_F(InputFilterInjectionPolicyTest,
3709 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3710 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3711 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3712 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003713}
3714
3715TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3716 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003717 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003718}
3719
chaviwfd6d3512019-03-25 13:23:49 -07003720class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003721 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003722 InputDispatcherTest::SetUp();
3723
Chris Yea209fde2020-07-22 13:54:51 -07003724 std::shared_ptr<FakeApplicationHandle> application =
3725 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003726 mUnfocusedWindow =
3727 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003728 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3729 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3730 // window.
chaviw3277faf2021-05-19 16:45:23 -05003731 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003732
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003733 mFocusedWindow =
3734 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3735 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003736 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003737
3738 // Set focused application.
3739 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003740 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003741
3742 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003744 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003745 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003746 }
3747
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003748 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003749 InputDispatcherTest::TearDown();
3750
3751 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003752 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003753 }
3754
3755protected:
3756 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003757 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003758 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003759};
3760
3761// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3762// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3763// the onPointerDownOutsideFocus callback.
3764TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003766 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3767 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003769 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003770
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003771 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003772 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3773}
3774
3775// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3776// DOWN on the window that doesn't have focus. Ensure no window received the
3777// onPointerDownOutsideFocus callback.
3778TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003781 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003782 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003783
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003784 ASSERT_TRUE(mDispatcher->waitForIdle());
3785 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003786}
3787
3788// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3789// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3790TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3792 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003793 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003794 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003795
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003796 ASSERT_TRUE(mDispatcher->waitForIdle());
3797 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003798}
3799
3800// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3801// DOWN on the window that already has focus. Ensure no window received the
3802// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003803TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003805 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003806 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003807 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003808 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003809
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003810 ASSERT_TRUE(mDispatcher->waitForIdle());
3811 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003812}
3813
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003814// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3815// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3816TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3817 const MotionEvent event =
3818 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3819 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3820 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3821 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3822 .build();
3823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3825 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3826
3827 ASSERT_TRUE(mDispatcher->waitForIdle());
3828 mFakePolicy->assertOnPointerDownWasNotCalled();
3829 // Ensure that the unfocused window did not receive any FOCUS events.
3830 mUnfocusedWindow->assertNoEvents();
3831}
3832
chaviwaf87b3e2019-10-01 16:59:28 -07003833// These tests ensures we can send touch events to a single client when there are multiple input
3834// windows that point to the same client token.
3835class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3836 virtual void SetUp() override {
3837 InputDispatcherTest::SetUp();
3838
Chris Yea209fde2020-07-22 13:54:51 -07003839 std::shared_ptr<FakeApplicationHandle> application =
3840 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003841 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3842 ADISPLAY_ID_DEFAULT);
3843 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3844 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003845 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003846 mWindow1->setFrame(Rect(0, 0, 100, 100));
3847
3848 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3849 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003850 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003851 mWindow2->setFrame(Rect(100, 100, 200, 200));
3852
Arthur Hung72d8dc32020-03-28 00:48:39 +00003853 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003854 }
3855
3856protected:
3857 sp<FakeWindowHandle> mWindow1;
3858 sp<FakeWindowHandle> mWindow2;
3859
3860 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003861 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003862 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3863 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003864 }
3865
3866 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3867 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003868 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003869 InputEvent* event = window->consume();
3870
3871 ASSERT_NE(nullptr, event) << name.c_str()
3872 << ": consumer should have returned non-NULL event.";
3873
3874 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3875 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3876 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3877
3878 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003879 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07003880
3881 for (size_t i = 0; i < points.size(); i++) {
3882 float expectedX = points[i].x;
3883 float expectedY = points[i].y;
3884
3885 EXPECT_EQ(expectedX, motionEvent.getX(i))
3886 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3887 << ", got " << motionEvent.getX(i);
3888 EXPECT_EQ(expectedY, motionEvent.getY(i))
3889 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3890 << ", got " << motionEvent.getY(i);
3891 }
3892 }
chaviw9eaa22c2020-07-01 16:21:27 -07003893
3894 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3895 std::vector<PointF> expectedPoints) {
3896 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3897 ADISPLAY_ID_DEFAULT, touchedPoints);
3898 mDispatcher->notifyMotion(&motionArgs);
3899
3900 // Always consume from window1 since it's the window that has the InputReceiver
3901 consumeMotionEvent(mWindow1, action, expectedPoints);
3902 }
chaviwaf87b3e2019-10-01 16:59:28 -07003903};
3904
3905TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3906 // Touch Window 1
3907 PointF touchedPoint = {10, 10};
3908 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003909 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003910
3911 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003912 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003913
3914 // Touch Window 2
3915 touchedPoint = {150, 150};
3916 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003917 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003918}
3919
chaviw9eaa22c2020-07-01 16:21:27 -07003920TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3921 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003922 mWindow2->setWindowScale(0.5f, 0.5f);
3923
3924 // Touch Window 1
3925 PointF touchedPoint = {10, 10};
3926 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003927 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003928 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003929 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003930
3931 // Touch Window 2
3932 touchedPoint = {150, 150};
3933 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003934 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3935 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003936
chaviw9eaa22c2020-07-01 16:21:27 -07003937 // Update the transform so rotation is set
3938 mWindow2->setWindowTransform(0, -1, 1, 0);
3939 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3940 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003941}
3942
chaviw9eaa22c2020-07-01 16:21:27 -07003943TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003944 mWindow2->setWindowScale(0.5f, 0.5f);
3945
3946 // Touch Window 1
3947 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3948 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003949 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003950
3951 // Touch Window 2
3952 int32_t actionPointerDown =
3953 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003954 touchedPoints.push_back(PointF{150, 150});
3955 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3956 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003957
chaviw9eaa22c2020-07-01 16:21:27 -07003958 // Release Window 2
3959 int32_t actionPointerUp =
3960 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3961 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3962 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003963
chaviw9eaa22c2020-07-01 16:21:27 -07003964 // Update the transform so rotation is set for Window 2
3965 mWindow2->setWindowTransform(0, -1, 1, 0);
3966 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3967 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003968}
3969
chaviw9eaa22c2020-07-01 16:21:27 -07003970TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003971 mWindow2->setWindowScale(0.5f, 0.5f);
3972
3973 // Touch Window 1
3974 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3975 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003976 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003977
3978 // Touch Window 2
3979 int32_t actionPointerDown =
3980 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003981 touchedPoints.push_back(PointF{150, 150});
3982 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003983
chaviw9eaa22c2020-07-01 16:21:27 -07003984 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003985
3986 // Move both windows
3987 touchedPoints = {{20, 20}, {175, 175}};
3988 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3989 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3990
chaviw9eaa22c2020-07-01 16:21:27 -07003991 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003992
chaviw9eaa22c2020-07-01 16:21:27 -07003993 // Release Window 2
3994 int32_t actionPointerUp =
3995 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3996 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3997 expectedPoints.pop_back();
3998
3999 // Touch Window 2
4000 mWindow2->setWindowTransform(0, -1, 1, 0);
4001 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4002 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4003
4004 // Move both windows
4005 touchedPoints = {{20, 20}, {175, 175}};
4006 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4007 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4008
4009 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004010}
4011
4012TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4013 mWindow1->setWindowScale(0.5f, 0.5f);
4014
4015 // Touch Window 1
4016 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4017 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004018 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004019
4020 // Touch Window 2
4021 int32_t actionPointerDown =
4022 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004023 touchedPoints.push_back(PointF{150, 150});
4024 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004025
chaviw9eaa22c2020-07-01 16:21:27 -07004026 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004027
4028 // Move both windows
4029 touchedPoints = {{20, 20}, {175, 175}};
4030 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4031 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4032
chaviw9eaa22c2020-07-01 16:21:27 -07004033 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004034}
4035
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004036class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4037 virtual void SetUp() override {
4038 InputDispatcherTest::SetUp();
4039
Chris Yea209fde2020-07-22 13:54:51 -07004040 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004041 mApplication->setDispatchingTimeout(20ms);
4042 mWindow =
4043 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4044 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004045 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004046 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004047 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4048 // window.
chaviw3277faf2021-05-19 16:45:23 -05004049 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004050
4051 // Set focused application.
4052 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4053
4054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004055 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004056 mWindow->consumeFocusEvent(true);
4057 }
4058
4059 virtual void TearDown() override {
4060 InputDispatcherTest::TearDown();
4061 mWindow.clear();
4062 }
4063
4064protected:
Chris Yea209fde2020-07-22 13:54:51 -07004065 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004066 sp<FakeWindowHandle> mWindow;
4067 static constexpr PointF WINDOW_LOCATION = {20, 20};
4068
4069 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004071 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4072 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004074 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4075 WINDOW_LOCATION));
4076 }
4077};
4078
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004079// Send a tap and respond, which should not cause an ANR.
4080TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4081 tapOnWindow();
4082 mWindow->consumeMotionDown();
4083 mWindow->consumeMotionUp();
4084 ASSERT_TRUE(mDispatcher->waitForIdle());
4085 mFakePolicy->assertNotifyAnrWasNotCalled();
4086}
4087
4088// Send a regular key and respond, which should not cause an ANR.
4089TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004091 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4092 ASSERT_TRUE(mDispatcher->waitForIdle());
4093 mFakePolicy->assertNotifyAnrWasNotCalled();
4094}
4095
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004096TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4097 mWindow->setFocusable(false);
4098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4099 mWindow->consumeFocusEvent(false);
4100
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004101 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004102 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004103 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4104 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004106 // Key will not go to window because we have no focused window.
4107 // The 'no focused window' ANR timer should start instead.
4108
4109 // Now, the focused application goes away.
4110 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4111 // The key should get dropped and there should be no ANR.
4112
4113 ASSERT_TRUE(mDispatcher->waitForIdle());
4114 mFakePolicy->assertNotifyAnrWasNotCalled();
4115}
4116
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004117// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004118// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4119// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004120TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004122 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4123 WINDOW_LOCATION));
4124
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004125 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4126 ASSERT_TRUE(sequenceNum);
4127 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004128 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004129
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004130 mWindow->finishEvent(*sequenceNum);
4131 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4132 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004133 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004134 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004135}
4136
4137// Send a key to the app and have the app not respond right away.
4138TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4139 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004141 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4142 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004143 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004144 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004145 ASSERT_TRUE(mDispatcher->waitForIdle());
4146}
4147
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004148// We have a focused application, but no focused window
4149TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004150 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4152 mWindow->consumeFocusEvent(false);
4153
4154 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004155 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004156 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4157 WINDOW_LOCATION));
4158 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4159 mDispatcher->waitForIdle();
4160 mFakePolicy->assertNotifyAnrWasNotCalled();
4161
4162 // Once a focused event arrives, we get an ANR for this application
4163 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4164 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004165 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004166 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004167 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004168 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004169 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004170 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004171 ASSERT_TRUE(mDispatcher->waitForIdle());
4172}
4173
4174// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004175// Make sure that we don't notify policy twice about the same ANR.
4176TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004177 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004178 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4179 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004180
4181 // Once a focused event arrives, we get an ANR for this application
4182 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4183 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004185 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004186 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004188 const std::chrono::duration appTimeout =
4189 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004190 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004191
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004192 std::this_thread::sleep_for(appTimeout);
4193 // ANR should not be raised again. It is up to policy to do that if it desires.
4194 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004195
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004196 // If we now get a focused window, the ANR should stop, but the policy handles that via
4197 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004198 ASSERT_TRUE(mDispatcher->waitForIdle());
4199}
4200
4201// We have a focused application, but no focused window
4202TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004203 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4205 mWindow->consumeFocusEvent(false);
4206
4207 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004208 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004209 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004210 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4211 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004212
4213 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004214 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004215
4216 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004217 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004218 ASSERT_TRUE(mDispatcher->waitForIdle());
4219 mWindow->assertNoEvents();
4220}
4221
4222/**
4223 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4224 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4225 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4226 * the ANR mechanism should still work.
4227 *
4228 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4229 * DOWN event, while not responding on the second one.
4230 */
4231TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4232 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4233 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4234 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4235 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4236 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004237 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004238
4239 // Now send ACTION_UP, with identical timestamp
4240 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4241 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4242 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4243 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004244 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004245
4246 // We have now sent down and up. Let's consume first event and then ANR on the second.
4247 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4248 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004249 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004250}
4251
4252// If an app is not responding to a key event, gesture monitors should continue to receive
4253// new motion events
4254TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4255 FakeMonitorReceiver monitor =
4256 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4257 true /*isGestureMonitor*/);
4258
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4260 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004261 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004263
4264 // Stuck on the ACTION_UP
4265 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004266 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004267
4268 // New tap will go to the gesture monitor, but not to the window
4269 tapOnWindow();
4270 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4271 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4272
4273 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4274 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004275 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004276 mWindow->assertNoEvents();
4277 monitor.assertNoEvents();
4278}
4279
4280// If an app is not responding to a motion event, gesture monitors should continue to receive
4281// new motion events
4282TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4283 FakeMonitorReceiver monitor =
4284 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4285 true /*isGestureMonitor*/);
4286
4287 tapOnWindow();
4288 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4289 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4290
4291 mWindow->consumeMotionDown();
4292 // Stuck on the ACTION_UP
4293 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004294 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004295
4296 // New tap will go to the gesture monitor, but not to the window
4297 tapOnWindow();
4298 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4299 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4300
4301 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4302 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004303 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004304 mWindow->assertNoEvents();
4305 monitor.assertNoEvents();
4306}
4307
4308// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4309// process events, you don't get an anr. When the window later becomes unresponsive again, you
4310// get an ANR again.
4311// 1. tap -> block on ACTION_UP -> receive ANR
4312// 2. consume all pending events (= queue becomes healthy again)
4313// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4314TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4315 tapOnWindow();
4316
4317 mWindow->consumeMotionDown();
4318 // Block on ACTION_UP
4319 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004320 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004321 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4322 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004323 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004324 mWindow->assertNoEvents();
4325
4326 tapOnWindow();
4327 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004328 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004329 mWindow->consumeMotionUp();
4330
4331 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004332 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004333 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004334 mWindow->assertNoEvents();
4335}
4336
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004337// If a connection remains unresponsive for a while, make sure policy is only notified once about
4338// it.
4339TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004341 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4342 WINDOW_LOCATION));
4343
4344 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004345 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004346 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004347 // 'notifyConnectionUnresponsive' should only be called once per connection
4348 mFakePolicy->assertNotifyAnrWasNotCalled();
4349 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004350 mWindow->consumeMotionDown();
4351 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4352 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4353 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004354 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004355 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004356 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004357}
4358
4359/**
4360 * If a window is processing a motion event, and then a key event comes in, the key event should
4361 * not to to the focused window until the motion is processed.
4362 *
4363 * Warning!!!
4364 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4365 * and the injection timeout that we specify when injecting the key.
4366 * We must have the injection timeout (10ms) be smaller than
4367 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4368 *
4369 * If that value changes, this test should also change.
4370 */
4371TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4372 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4374
4375 tapOnWindow();
4376 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4377 ASSERT_TRUE(downSequenceNum);
4378 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4379 ASSERT_TRUE(upSequenceNum);
4380 // Don't finish the events yet, and send a key
4381 // Injection will "succeed" because we will eventually give up and send the key to the focused
4382 // window even if motions are still being processed. But because the injection timeout is short,
4383 // we will receive INJECTION_TIMED_OUT as the result.
4384
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004386 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4388 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004389 // Key will not be sent to the window, yet, because the window is still processing events
4390 // and the key remains pending, waiting for the touch events to be processed
4391 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4392 ASSERT_FALSE(keySequenceNum);
4393
4394 std::this_thread::sleep_for(500ms);
4395 // if we wait long enough though, dispatcher will give up, and still send the key
4396 // to the focused window, even though we have not yet finished the motion event
4397 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4398 mWindow->finishEvent(*downSequenceNum);
4399 mWindow->finishEvent(*upSequenceNum);
4400}
4401
4402/**
4403 * If a window is processing a motion event, and then a key event comes in, the key event should
4404 * not go to the focused window until the motion is processed.
4405 * If then a new motion comes in, then the pending key event should be going to the currently
4406 * focused window right away.
4407 */
4408TEST_F(InputDispatcherSingleWindowAnr,
4409 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4410 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4412
4413 tapOnWindow();
4414 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4415 ASSERT_TRUE(downSequenceNum);
4416 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4417 ASSERT_TRUE(upSequenceNum);
4418 // Don't finish the events yet, and send a key
4419 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004421 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004422 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423 // At this point, key is still pending, and should not be sent to the application yet.
4424 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4425 ASSERT_FALSE(keySequenceNum);
4426
4427 // Now tap down again. It should cause the pending key to go to the focused window right away.
4428 tapOnWindow();
4429 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4430 // the other events yet. We can finish events in any order.
4431 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4432 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4433 mWindow->consumeMotionDown();
4434 mWindow->consumeMotionUp();
4435 mWindow->assertNoEvents();
4436}
4437
4438class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4439 virtual void SetUp() override {
4440 InputDispatcherTest::SetUp();
4441
Chris Yea209fde2020-07-22 13:54:51 -07004442 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004443 mApplication->setDispatchingTimeout(10ms);
4444 mUnfocusedWindow =
4445 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4446 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4447 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4448 // window.
4449 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004450 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4451 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4452 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004453
4454 mFocusedWindow =
4455 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004456 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004458 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459
4460 // Set focused application.
4461 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004462 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004463
4464 // Expect one focus window exist in display.
4465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004466 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004467 mFocusedWindow->consumeFocusEvent(true);
4468 }
4469
4470 virtual void TearDown() override {
4471 InputDispatcherTest::TearDown();
4472
4473 mUnfocusedWindow.clear();
4474 mFocusedWindow.clear();
4475 }
4476
4477protected:
Chris Yea209fde2020-07-22 13:54:51 -07004478 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479 sp<FakeWindowHandle> mUnfocusedWindow;
4480 sp<FakeWindowHandle> mFocusedWindow;
4481 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4482 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4483 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4484
4485 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4486
4487 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4488
4489private:
4490 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004491 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4493 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4496 location));
4497 }
4498};
4499
4500// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4501// should be ANR'd first.
4502TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004504 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4505 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004507 mFocusedWindow->consumeMotionDown();
4508 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4509 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4510 // We consumed all events, so no ANR
4511 ASSERT_TRUE(mDispatcher->waitForIdle());
4512 mFakePolicy->assertNotifyAnrWasNotCalled();
4513
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004515 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4516 FOCUSED_WINDOW_LOCATION));
4517 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4518 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004519
4520 const std::chrono::duration timeout =
4521 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004522 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004523 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4524 // sequence to make it consistent
4525 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004526 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004527 mFocusedWindow->consumeMotionDown();
4528 // This cancel is generated because the connection was unresponsive
4529 mFocusedWindow->consumeMotionCancel();
4530 mFocusedWindow->assertNoEvents();
4531 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004533 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004534 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535}
4536
4537// If we have 2 windows with identical timeouts that are both unresponsive,
4538// it doesn't matter which order they should have ANR.
4539// But we should receive ANR for both.
4540TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4541 // Set the timeout for unfocused window to match the focused window
4542 mUnfocusedWindow->setDispatchingTimeout(10ms);
4543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4544
4545 tapOnFocusedWindow();
4546 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004547 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4548 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549
4550 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004551 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4552 mFocusedWindow->getToken() == anrConnectionToken2);
4553 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4554 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 ASSERT_TRUE(mDispatcher->waitForIdle());
4557 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004558
4559 mFocusedWindow->consumeMotionDown();
4560 mFocusedWindow->consumeMotionUp();
4561 mUnfocusedWindow->consumeMotionOutside();
4562
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004563 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4564 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004565
4566 // Both applications should be marked as responsive, in any order
4567 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4568 mFocusedWindow->getToken() == responsiveToken2);
4569 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4570 mUnfocusedWindow->getToken() == responsiveToken2);
4571 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004572}
4573
4574// If a window is already not responding, the second tap on the same window should be ignored.
4575// We should also log an error to account for the dropped event (not tested here).
4576// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4577TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4578 tapOnFocusedWindow();
4579 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4580 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4581 // Receive the events, but don't respond
4582 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4583 ASSERT_TRUE(downEventSequenceNum);
4584 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4585 ASSERT_TRUE(upEventSequenceNum);
4586 const std::chrono::duration timeout =
4587 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004588 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004589
4590 // Tap once again
4591 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004592 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4594 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004595 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004596 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4597 FOCUSED_WINDOW_LOCATION));
4598 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4599 // valid touch target
4600 mUnfocusedWindow->assertNoEvents();
4601
4602 // Consume the first tap
4603 mFocusedWindow->finishEvent(*downEventSequenceNum);
4604 mFocusedWindow->finishEvent(*upEventSequenceNum);
4605 ASSERT_TRUE(mDispatcher->waitForIdle());
4606 // The second tap did not go to the focused window
4607 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004608 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004609 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004610 mFakePolicy->assertNotifyAnrWasNotCalled();
4611}
4612
4613// If you tap outside of all windows, there will not be ANR
4614TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004615 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4617 LOCATION_OUTSIDE_ALL_WINDOWS));
4618 ASSERT_TRUE(mDispatcher->waitForIdle());
4619 mFakePolicy->assertNotifyAnrWasNotCalled();
4620}
4621
4622// Since the focused window is paused, tapping on it should not produce any events
4623TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4624 mFocusedWindow->setPaused(true);
4625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4626
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004627 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4629 FOCUSED_WINDOW_LOCATION));
4630
4631 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4632 ASSERT_TRUE(mDispatcher->waitForIdle());
4633 // Should not ANR because the window is paused, and touches shouldn't go to it
4634 mFakePolicy->assertNotifyAnrWasNotCalled();
4635
4636 mFocusedWindow->assertNoEvents();
4637 mUnfocusedWindow->assertNoEvents();
4638}
4639
4640/**
4641 * If a window is processing a motion event, and then a key event comes in, the key event should
4642 * not to to the focused window until the motion is processed.
4643 * If a different window becomes focused at this time, the key should go to that window instead.
4644 *
4645 * Warning!!!
4646 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4647 * and the injection timeout that we specify when injecting the key.
4648 * We must have the injection timeout (10ms) be smaller than
4649 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4650 *
4651 * If that value changes, this test should also change.
4652 */
4653TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4654 // Set a long ANR timeout to prevent it from triggering
4655 mFocusedWindow->setDispatchingTimeout(2s);
4656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4657
4658 tapOnUnfocusedWindow();
4659 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4660 ASSERT_TRUE(downSequenceNum);
4661 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4662 ASSERT_TRUE(upSequenceNum);
4663 // Don't finish the events yet, and send a key
4664 // Injection will succeed because we will eventually give up and send the key to the focused
4665 // window even if motions are still being processed.
4666
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004667 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004669 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004671 // Key will not be sent to the window, yet, because the window is still processing events
4672 // and the key remains pending, waiting for the touch events to be processed
4673 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4674 ASSERT_FALSE(keySequenceNum);
4675
4676 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004677 mFocusedWindow->setFocusable(false);
4678 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004680 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681
4682 // Focus events should precede the key events
4683 mUnfocusedWindow->consumeFocusEvent(true);
4684 mFocusedWindow->consumeFocusEvent(false);
4685
4686 // Finish the tap events, which should unblock dispatcher
4687 mUnfocusedWindow->finishEvent(*downSequenceNum);
4688 mUnfocusedWindow->finishEvent(*upSequenceNum);
4689
4690 // Now that all queues are cleared and no backlog in the connections, the key event
4691 // can finally go to the newly focused "mUnfocusedWindow".
4692 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4693 mFocusedWindow->assertNoEvents();
4694 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004695 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004696}
4697
4698// When the touch stream is split across 2 windows, and one of them does not respond,
4699// then ANR should be raised and the touch should be canceled for the unresponsive window.
4700// The other window should not be affected by that.
4701TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4702 // Touch Window 1
4703 NotifyMotionArgs motionArgs =
4704 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4705 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4706 mDispatcher->notifyMotion(&motionArgs);
4707 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4708 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4709
4710 // Touch Window 2
4711 int32_t actionPointerDown =
4712 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4713
4714 motionArgs =
4715 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4716 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4717 mDispatcher->notifyMotion(&motionArgs);
4718
4719 const std::chrono::duration timeout =
4720 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004721 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722
4723 mUnfocusedWindow->consumeMotionDown();
4724 mFocusedWindow->consumeMotionDown();
4725 // Focused window may or may not receive ACTION_MOVE
4726 // But it should definitely receive ACTION_CANCEL due to the ANR
4727 InputEvent* event;
4728 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4729 ASSERT_TRUE(moveOrCancelSequenceNum);
4730 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4731 ASSERT_NE(nullptr, event);
4732 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4733 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4734 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4735 mFocusedWindow->consumeMotionCancel();
4736 } else {
4737 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4738 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004740 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004741
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 mUnfocusedWindow->assertNoEvents();
4743 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004744 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745}
4746
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004747/**
4748 * If we have no focused window, and a key comes in, we start the ANR timer.
4749 * The focused application should add a focused window before the timer runs out to prevent ANR.
4750 *
4751 * If the user touches another application during this time, the key should be dropped.
4752 * Next, if a new focused window comes in, without toggling the focused application,
4753 * then no ANR should occur.
4754 *
4755 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4756 * but in some cases the policy may not update the focused application.
4757 */
4758TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4759 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4760 std::make_shared<FakeApplicationHandle>();
4761 focusedApplication->setDispatchingTimeout(60ms);
4762 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4763 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4764 mFocusedWindow->setFocusable(false);
4765
4766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4767 mFocusedWindow->consumeFocusEvent(false);
4768
4769 // Send a key. The ANR timer should start because there is no focused window.
4770 // 'focusedApplication' will get blamed if this timer completes.
4771 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004772 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004773 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004774 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4775 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004777
4778 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4779 // then the injected touches won't cause the focused event to get dropped.
4780 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4781 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4782 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4783 // For this test, it means that the key would get delivered to the window once it becomes
4784 // focused.
4785 std::this_thread::sleep_for(10ms);
4786
4787 // Touch unfocused window. This should force the pending key to get dropped.
4788 NotifyMotionArgs motionArgs =
4789 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4790 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4791 mDispatcher->notifyMotion(&motionArgs);
4792
4793 // We do not consume the motion right away, because that would require dispatcher to first
4794 // process (== drop) the key event, and by that time, ANR will be raised.
4795 // Set the focused window first.
4796 mFocusedWindow->setFocusable(true);
4797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4798 setFocusedWindow(mFocusedWindow);
4799 mFocusedWindow->consumeFocusEvent(true);
4800 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4801 // to another application. This could be a bug / behaviour in the policy.
4802
4803 mUnfocusedWindow->consumeMotionDown();
4804
4805 ASSERT_TRUE(mDispatcher->waitForIdle());
4806 // Should not ANR because we actually have a focused window. It was just added too slowly.
4807 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4808}
4809
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004810// These tests ensure we cannot send touch events to a window that's positioned behind a window
4811// that has feature NO_INPUT_CHANNEL.
4812// Layout:
4813// Top (closest to user)
4814// mNoInputWindow (above all windows)
4815// mBottomWindow
4816// Bottom (furthest from user)
4817class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4818 virtual void SetUp() override {
4819 InputDispatcherTest::SetUp();
4820
4821 mApplication = std::make_shared<FakeApplicationHandle>();
4822 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4823 "Window without input channel", ADISPLAY_ID_DEFAULT,
4824 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4825
chaviw3277faf2021-05-19 16:45:23 -05004826 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004827 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4828 // It's perfectly valid for this window to not have an associated input channel
4829
4830 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4831 ADISPLAY_ID_DEFAULT);
4832 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4833
4834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4835 }
4836
4837protected:
4838 std::shared_ptr<FakeApplicationHandle> mApplication;
4839 sp<FakeWindowHandle> mNoInputWindow;
4840 sp<FakeWindowHandle> mBottomWindow;
4841};
4842
4843TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4844 PointF touchedPoint = {10, 10};
4845
4846 NotifyMotionArgs motionArgs =
4847 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4848 ADISPLAY_ID_DEFAULT, {touchedPoint});
4849 mDispatcher->notifyMotion(&motionArgs);
4850
4851 mNoInputWindow->assertNoEvents();
4852 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4853 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4854 // and therefore should prevent mBottomWindow from receiving touches
4855 mBottomWindow->assertNoEvents();
4856}
4857
4858/**
4859 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4860 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4861 */
4862TEST_F(InputDispatcherMultiWindowOcclusionTests,
4863 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4864 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4865 "Window with input channel and NO_INPUT_CHANNEL",
4866 ADISPLAY_ID_DEFAULT);
4867
chaviw3277faf2021-05-19 16:45:23 -05004868 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004869 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4871
4872 PointF touchedPoint = {10, 10};
4873
4874 NotifyMotionArgs motionArgs =
4875 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4876 ADISPLAY_ID_DEFAULT, {touchedPoint});
4877 mDispatcher->notifyMotion(&motionArgs);
4878
4879 mNoInputWindow->assertNoEvents();
4880 mBottomWindow->assertNoEvents();
4881}
4882
Vishnu Nair958da932020-08-21 17:12:37 -07004883class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4884protected:
4885 std::shared_ptr<FakeApplicationHandle> mApp;
4886 sp<FakeWindowHandle> mWindow;
4887 sp<FakeWindowHandle> mMirror;
4888
4889 virtual void SetUp() override {
4890 InputDispatcherTest::SetUp();
4891 mApp = std::make_shared<FakeApplicationHandle>();
4892 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4893 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4894 mWindow->getToken());
4895 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4896 mWindow->setFocusable(true);
4897 mMirror->setFocusable(true);
4898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4899 }
4900};
4901
4902TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4903 // Request focus on a mirrored window
4904 setFocusedWindow(mMirror);
4905
4906 // window gets focused
4907 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4909 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004910 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4911}
4912
4913// A focused & mirrored window remains focused only if the window and its mirror are both
4914// focusable.
4915TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4916 setFocusedWindow(mMirror);
4917
4918 // window gets focused
4919 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4921 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004922 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004923 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4924 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004925 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4926
4927 mMirror->setFocusable(false);
4928 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4929
4930 // window loses focus since one of the windows associated with the token in not focusable
4931 mWindow->consumeFocusEvent(false);
4932
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004933 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4934 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004935 mWindow->assertNoEvents();
4936}
4937
4938// A focused & mirrored window remains focused until the window and its mirror both become
4939// invisible.
4940TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4941 setFocusedWindow(mMirror);
4942
4943 // window gets focused
4944 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4946 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004947 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4949 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004950 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4951
4952 mMirror->setVisible(false);
4953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4954
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4956 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004957 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4959 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004960 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4961
4962 mWindow->setVisible(false);
4963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4964
4965 // window loses focus only after all windows associated with the token become invisible.
4966 mWindow->consumeFocusEvent(false);
4967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004968 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4969 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004970 mWindow->assertNoEvents();
4971}
4972
4973// A focused & mirrored window remains focused until both windows are removed.
4974TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4975 setFocusedWindow(mMirror);
4976
4977 // window gets focused
4978 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4980 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004981 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4983 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004984 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4985
4986 // single window is removed but the window token remains focused
4987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4990 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004991 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4993 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004994 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4995
4996 // Both windows are removed
4997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4998 mWindow->consumeFocusEvent(false);
4999
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005000 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5001 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005002 mWindow->assertNoEvents();
5003}
5004
5005// Focus request can be pending until one window becomes visible.
5006TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5007 // Request focus on an invisible mirror.
5008 mWindow->setVisible(false);
5009 mMirror->setVisible(false);
5010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5011 setFocusedWindow(mMirror);
5012
5013 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005015 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005016 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005017
5018 mMirror->setVisible(true);
5019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5020
5021 // window gets focused
5022 mWindow->consumeFocusEvent(true);
5023 // window gets the pending key event
5024 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5025}
Prabir Pradhan99987712020-11-10 18:43:05 -08005026
5027class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5028protected:
5029 std::shared_ptr<FakeApplicationHandle> mApp;
5030 sp<FakeWindowHandle> mWindow;
5031 sp<FakeWindowHandle> mSecondWindow;
5032
5033 void SetUp() override {
5034 InputDispatcherTest::SetUp();
5035 mApp = std::make_shared<FakeApplicationHandle>();
5036 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5037 mWindow->setFocusable(true);
5038 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5039 mSecondWindow->setFocusable(true);
5040
5041 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5043
5044 setFocusedWindow(mWindow);
5045 mWindow->consumeFocusEvent(true);
5046 }
5047
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005048 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5049 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005050 mDispatcher->notifyPointerCaptureChanged(&args);
5051 }
5052
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005053 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5054 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005055 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005056 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5057 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005058 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005059 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005060 }
5061};
5062
5063TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5064 // Ensure that capture cannot be obtained for unfocused windows.
5065 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5066 mFakePolicy->assertSetPointerCaptureNotCalled();
5067 mSecondWindow->assertNoEvents();
5068
5069 // Ensure that capture can be enabled from the focus window.
5070 requestAndVerifyPointerCapture(mWindow, true);
5071
5072 // Ensure that capture cannot be disabled from a window that does not have capture.
5073 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5074 mFakePolicy->assertSetPointerCaptureNotCalled();
5075
5076 // Ensure that capture can be disabled from the window with capture.
5077 requestAndVerifyPointerCapture(mWindow, false);
5078}
5079
5080TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005081 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005082
5083 setFocusedWindow(mSecondWindow);
5084
5085 // Ensure that the capture disabled event was sent first.
5086 mWindow->consumeCaptureEvent(false);
5087 mWindow->consumeFocusEvent(false);
5088 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005089 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005090
5091 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005092 notifyPointerCaptureChanged({});
5093 notifyPointerCaptureChanged(request);
5094 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005095 mWindow->assertNoEvents();
5096 mSecondWindow->assertNoEvents();
5097 mFakePolicy->assertSetPointerCaptureNotCalled();
5098}
5099
5100TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005101 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005102
5103 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005104 notifyPointerCaptureChanged({});
5105 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005106
5107 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005108 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005109 mWindow->consumeCaptureEvent(false);
5110 mWindow->assertNoEvents();
5111}
5112
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005113TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5114 requestAndVerifyPointerCapture(mWindow, true);
5115
5116 // The first window loses focus.
5117 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005118 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005119 mWindow->consumeCaptureEvent(false);
5120
5121 // Request Pointer Capture from the second window before the notification from InputReader
5122 // arrives.
5123 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005124 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005125
5126 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005127 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005128
5129 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005130 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005131
5132 mSecondWindow->consumeFocusEvent(true);
5133 mSecondWindow->consumeCaptureEvent(true);
5134}
5135
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005136TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5137 // App repeatedly enables and disables capture.
5138 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5139 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5140 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5141 mFakePolicy->assertSetPointerCaptureCalled(false);
5142 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5143 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5144
5145 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5146 // first request is now stale, this should do nothing.
5147 notifyPointerCaptureChanged(firstRequest);
5148 mWindow->assertNoEvents();
5149
5150 // InputReader notifies that the second request was enabled.
5151 notifyPointerCaptureChanged(secondRequest);
5152 mWindow->consumeCaptureEvent(true);
5153}
5154
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005155class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5156protected:
5157 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005158
5159 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5160 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5161
5162 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5163 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5164
5165 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5166 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5167 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5168 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5169 MAXIMUM_OBSCURING_OPACITY);
5170
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005171 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005172 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005173 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005174
5175 sp<FakeWindowHandle> mTouchWindow;
5176
5177 virtual void SetUp() override {
5178 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005179 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005180 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5181 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5182 }
5183
5184 virtual void TearDown() override {
5185 InputDispatcherTest::TearDown();
5186 mTouchWindow.clear();
5187 }
5188
chaviw3277faf2021-05-19 16:45:23 -05005189 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5190 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005191 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005192 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005193 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005194 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005195 return window;
5196 }
5197
5198 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5199 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5200 sp<FakeWindowHandle> window =
5201 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5202 // Generate an arbitrary PID based on the UID
5203 window->setOwnerInfo(1777 + (uid % 10000), uid);
5204 return window;
5205 }
5206
5207 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5208 NotifyMotionArgs args =
5209 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5210 ADISPLAY_ID_DEFAULT, points);
5211 mDispatcher->notifyMotion(&args);
5212 }
5213};
5214
5215TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005216 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005217 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005219
5220 touch();
5221
5222 mTouchWindow->assertNoEvents();
5223}
5224
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005225TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005226 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5227 const sp<FakeWindowHandle>& w =
5228 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5230
5231 touch();
5232
5233 mTouchWindow->assertNoEvents();
5234}
5235
5236TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005237 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5238 const sp<FakeWindowHandle>& w =
5239 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5241
5242 touch();
5243
5244 w->assertNoEvents();
5245}
5246
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005247TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005248 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005250
5251 touch();
5252
5253 mTouchWindow->consumeAnyMotionDown();
5254}
5255
5256TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005257 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005258 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005259 w->setFrame(Rect(0, 0, 50, 50));
5260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005261
5262 touch({PointF{100, 100}});
5263
5264 mTouchWindow->consumeAnyMotionDown();
5265}
5266
5267TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005268 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005269 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5271
5272 touch();
5273
5274 mTouchWindow->consumeAnyMotionDown();
5275}
5276
5277TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5278 const sp<FakeWindowHandle>& w =
5279 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5280 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005281
5282 touch();
5283
5284 mTouchWindow->consumeAnyMotionDown();
5285}
5286
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005287TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5288 const sp<FakeWindowHandle>& w =
5289 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5291
5292 touch();
5293
5294 w->assertNoEvents();
5295}
5296
5297/**
5298 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5299 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5300 * window, the occluding window will still receive ACTION_OUTSIDE event.
5301 */
5302TEST_F(InputDispatcherUntrustedTouchesTest,
5303 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5304 const sp<FakeWindowHandle>& w =
5305 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005306 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5308
5309 touch();
5310
5311 w->consumeMotionOutside();
5312}
5313
5314TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5315 const sp<FakeWindowHandle>& w =
5316 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005317 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5319
5320 touch();
5321
5322 InputEvent* event = w->consume();
5323 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5324 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5325 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5326 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5327}
5328
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005329TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005330 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005331 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5332 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5334
5335 touch();
5336
5337 mTouchWindow->consumeAnyMotionDown();
5338}
5339
5340TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5341 const sp<FakeWindowHandle>& w =
5342 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5343 MAXIMUM_OBSCURING_OPACITY);
5344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005345
5346 touch();
5347
5348 mTouchWindow->consumeAnyMotionDown();
5349}
5350
5351TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005352 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005353 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5354 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5356
5357 touch();
5358
5359 mTouchWindow->assertNoEvents();
5360}
5361
5362TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5363 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5364 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005365 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5366 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005367 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005368 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5369 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5371
5372 touch();
5373
5374 mTouchWindow->assertNoEvents();
5375}
5376
5377TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5378 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5379 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005380 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5381 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005382 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005383 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5384 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5386
5387 touch();
5388
5389 mTouchWindow->consumeAnyMotionDown();
5390}
5391
5392TEST_F(InputDispatcherUntrustedTouchesTest,
5393 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5394 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005395 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5396 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005397 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005398 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5399 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5401
5402 touch();
5403
5404 mTouchWindow->consumeAnyMotionDown();
5405}
5406
5407TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5408 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005409 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5410 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005411 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005412 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5413 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005415
5416 touch();
5417
5418 mTouchWindow->assertNoEvents();
5419}
5420
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005421TEST_F(InputDispatcherUntrustedTouchesTest,
5422 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5423 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005424 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5425 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005426 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005427 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5428 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5430
5431 touch();
5432
5433 mTouchWindow->assertNoEvents();
5434}
5435
5436TEST_F(InputDispatcherUntrustedTouchesTest,
5437 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5438 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005439 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5440 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005441 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005442 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5443 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5445
5446 touch();
5447
5448 mTouchWindow->consumeAnyMotionDown();
5449}
5450
5451TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5452 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005453 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5454 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5456
5457 touch();
5458
5459 mTouchWindow->consumeAnyMotionDown();
5460}
5461
5462TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5463 const sp<FakeWindowHandle>& w =
5464 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5466
5467 touch();
5468
5469 mTouchWindow->consumeAnyMotionDown();
5470}
5471
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005472TEST_F(InputDispatcherUntrustedTouchesTest,
5473 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5474 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5475 const sp<FakeWindowHandle>& w =
5476 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5478
5479 touch();
5480
5481 mTouchWindow->assertNoEvents();
5482}
5483
5484TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5485 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5486 const sp<FakeWindowHandle>& w =
5487 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5489
5490 touch();
5491
5492 mTouchWindow->consumeAnyMotionDown();
5493}
5494
5495TEST_F(InputDispatcherUntrustedTouchesTest,
5496 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5497 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5498 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005499 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5500 OPACITY_ABOVE_THRESHOLD);
5501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5502
5503 touch();
5504
5505 mTouchWindow->consumeAnyMotionDown();
5506}
5507
5508TEST_F(InputDispatcherUntrustedTouchesTest,
5509 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5510 const sp<FakeWindowHandle>& w1 =
5511 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5512 OPACITY_BELOW_THRESHOLD);
5513 const sp<FakeWindowHandle>& w2 =
5514 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5515 OPACITY_BELOW_THRESHOLD);
5516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5517
5518 touch();
5519
5520 mTouchWindow->assertNoEvents();
5521}
5522
5523/**
5524 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5525 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5526 * (which alone would result in allowing touches) does not affect the blocking behavior.
5527 */
5528TEST_F(InputDispatcherUntrustedTouchesTest,
5529 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5530 const sp<FakeWindowHandle>& wB =
5531 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5532 OPACITY_BELOW_THRESHOLD);
5533 const sp<FakeWindowHandle>& wC =
5534 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5535 OPACITY_BELOW_THRESHOLD);
5536 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5537
5538 touch();
5539
5540 mTouchWindow->assertNoEvents();
5541}
5542
5543/**
5544 * This test is testing that a window from a different UID but with same application token doesn't
5545 * block the touch. Apps can share the application token for close UI collaboration for example.
5546 */
5547TEST_F(InputDispatcherUntrustedTouchesTest,
5548 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5549 const sp<FakeWindowHandle>& w =
5550 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5551 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005552 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5553
5554 touch();
5555
5556 mTouchWindow->consumeAnyMotionDown();
5557}
5558
arthurhungb89ccb02020-12-30 16:19:01 +08005559class InputDispatcherDragTests : public InputDispatcherTest {
5560protected:
5561 std::shared_ptr<FakeApplicationHandle> mApp;
5562 sp<FakeWindowHandle> mWindow;
5563 sp<FakeWindowHandle> mSecondWindow;
5564 sp<FakeWindowHandle> mDragWindow;
5565
5566 void SetUp() override {
5567 InputDispatcherTest::SetUp();
5568 mApp = std::make_shared<FakeApplicationHandle>();
5569 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5570 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005571 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005572
5573 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5574 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005575 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005576
5577 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5579 }
5580
5581 // Start performing drag, we will create a drag window and transfer touch to it.
5582 void performDrag() {
5583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5585 {50, 50}))
5586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5587
5588 // Window should receive motion event.
5589 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5590
5591 // The drag window covers the entire display
5592 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5593 mDispatcher->setInputWindows(
5594 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5595
5596 // Transfer touch focus to the drag window
5597 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5598 true /* isDragDrop */);
5599 mWindow->consumeMotionCancel();
5600 mDragWindow->consumeMotionDown();
5601 }
arthurhung6d4bed92021-03-17 11:59:33 +08005602
5603 // Start performing drag, we will create a drag window and transfer touch to it.
5604 void performStylusDrag() {
5605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5606 injectMotionEvent(mDispatcher,
5607 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5608 AINPUT_SOURCE_STYLUS)
5609 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5610 .pointer(PointerBuilder(0,
5611 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5612 .x(50)
5613 .y(50))
5614 .build()));
5615 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5616
5617 // The drag window covers the entire display
5618 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5619 mDispatcher->setInputWindows(
5620 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5621
5622 // Transfer touch focus to the drag window
5623 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5624 true /* isDragDrop */);
5625 mWindow->consumeMotionCancel();
5626 mDragWindow->consumeMotionDown();
5627 }
arthurhungb89ccb02020-12-30 16:19:01 +08005628};
5629
5630TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5631 performDrag();
5632
5633 // Move on window.
5634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5635 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5636 ADISPLAY_ID_DEFAULT, {50, 50}))
5637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5638 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5639 mWindow->consumeDragEvent(false, 50, 50);
5640 mSecondWindow->assertNoEvents();
5641
5642 // Move to another window.
5643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5644 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5645 ADISPLAY_ID_DEFAULT, {150, 50}))
5646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5647 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5648 mWindow->consumeDragEvent(true, 150, 50);
5649 mSecondWindow->consumeDragEvent(false, 50, 50);
5650
5651 // Move back to original window.
5652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5653 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5654 ADISPLAY_ID_DEFAULT, {50, 50}))
5655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5656 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5657 mWindow->consumeDragEvent(false, 50, 50);
5658 mSecondWindow->consumeDragEvent(true, -50, 50);
5659
5660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5661 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5662 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5663 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5664 mWindow->assertNoEvents();
5665 mSecondWindow->assertNoEvents();
5666}
5667
arthurhungf452d0b2021-01-06 00:19:52 +08005668TEST_F(InputDispatcherDragTests, DragAndDrop) {
5669 performDrag();
5670
5671 // Move on window.
5672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5673 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5674 ADISPLAY_ID_DEFAULT, {50, 50}))
5675 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5676 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5677 mWindow->consumeDragEvent(false, 50, 50);
5678 mSecondWindow->assertNoEvents();
5679
5680 // Move to another window.
5681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5682 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5683 ADISPLAY_ID_DEFAULT, {150, 50}))
5684 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5685 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5686 mWindow->consumeDragEvent(true, 150, 50);
5687 mSecondWindow->consumeDragEvent(false, 50, 50);
5688
5689 // drop to another window.
5690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5691 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5692 {150, 50}))
5693 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5694 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5695 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5696 mWindow->assertNoEvents();
5697 mSecondWindow->assertNoEvents();
5698}
5699
arthurhung6d4bed92021-03-17 11:59:33 +08005700TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5701 performStylusDrag();
5702
5703 // Move on window and keep button pressed.
5704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5705 injectMotionEvent(mDispatcher,
5706 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5707 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5708 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5709 .x(50)
5710 .y(50))
5711 .build()))
5712 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5713 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5714 mWindow->consumeDragEvent(false, 50, 50);
5715 mSecondWindow->assertNoEvents();
5716
5717 // Move to another window and release button, expect to drop item.
5718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5719 injectMotionEvent(mDispatcher,
5720 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5721 .buttonState(0)
5722 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5723 .x(150)
5724 .y(50))
5725 .build()))
5726 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5727 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5728 mWindow->assertNoEvents();
5729 mSecondWindow->assertNoEvents();
5730 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5731
5732 // nothing to the window.
5733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5734 injectMotionEvent(mDispatcher,
5735 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5736 .buttonState(0)
5737 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5738 .x(150)
5739 .y(50))
5740 .build()))
5741 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5742 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5743 mWindow->assertNoEvents();
5744 mSecondWindow->assertNoEvents();
5745}
5746
Arthur Hung6d0571e2021-04-09 20:18:16 +08005747TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5748 performDrag();
5749
5750 // Set second window invisible.
5751 mSecondWindow->setVisible(false);
5752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5753
5754 // Move on window.
5755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5756 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5757 ADISPLAY_ID_DEFAULT, {50, 50}))
5758 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5759 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5760 mWindow->consumeDragEvent(false, 50, 50);
5761 mSecondWindow->assertNoEvents();
5762
5763 // Move to another window.
5764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5765 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5766 ADISPLAY_ID_DEFAULT, {150, 50}))
5767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5768 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5769 mWindow->consumeDragEvent(true, 150, 50);
5770 mSecondWindow->assertNoEvents();
5771
5772 // drop to another window.
5773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5774 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5775 {150, 50}))
5776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5777 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5778 mFakePolicy->assertDropTargetEquals(nullptr);
5779 mWindow->assertNoEvents();
5780 mSecondWindow->assertNoEvents();
5781}
5782
Vishnu Nair062a8672021-09-03 16:07:44 -07005783class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5784
5785TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5786 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5787 sp<FakeWindowHandle> window =
5788 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5789 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5790 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5791 window->setFocusable(true);
5792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5793 setFocusedWindow(window);
5794 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5795
5796 // With the flag set, window should not get any input
5797 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5798 mDispatcher->notifyKey(&keyArgs);
5799 window->assertNoEvents();
5800
5801 NotifyMotionArgs motionArgs =
5802 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5803 ADISPLAY_ID_DEFAULT);
5804 mDispatcher->notifyMotion(&motionArgs);
5805 window->assertNoEvents();
5806
5807 // With the flag cleared, the window should get input
5808 window->setInputFeatures({});
5809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5810
5811 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5812 mDispatcher->notifyKey(&keyArgs);
5813 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5814
5815 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5816 ADISPLAY_ID_DEFAULT);
5817 mDispatcher->notifyMotion(&motionArgs);
5818 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5819 window->assertNoEvents();
5820}
5821
5822TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5823 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5824 std::make_shared<FakeApplicationHandle>();
5825 sp<FakeWindowHandle> obscuringWindow =
5826 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5827 ADISPLAY_ID_DEFAULT);
5828 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5829 obscuringWindow->setOwnerInfo(111, 111);
5830 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5831 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5832 sp<FakeWindowHandle> window =
5833 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5834 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5835 window->setOwnerInfo(222, 222);
5836 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5837 window->setFocusable(true);
5838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5839 setFocusedWindow(window);
5840 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5841
5842 // With the flag set, window should not get any input
5843 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5844 mDispatcher->notifyKey(&keyArgs);
5845 window->assertNoEvents();
5846
5847 NotifyMotionArgs motionArgs =
5848 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5849 ADISPLAY_ID_DEFAULT);
5850 mDispatcher->notifyMotion(&motionArgs);
5851 window->assertNoEvents();
5852
5853 // With the flag cleared, the window should get input
5854 window->setInputFeatures({});
5855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5856
5857 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5858 mDispatcher->notifyKey(&keyArgs);
5859 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5860
5861 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5862 ADISPLAY_ID_DEFAULT);
5863 mDispatcher->notifyMotion(&motionArgs);
5864 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5865 window->assertNoEvents();
5866}
5867
5868TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5869 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5870 std::make_shared<FakeApplicationHandle>();
5871 sp<FakeWindowHandle> obscuringWindow =
5872 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5873 ADISPLAY_ID_DEFAULT);
5874 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5875 obscuringWindow->setOwnerInfo(111, 111);
5876 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5877 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5878 sp<FakeWindowHandle> window =
5879 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5880 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5881 window->setOwnerInfo(222, 222);
5882 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5883 window->setFocusable(true);
5884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5885 setFocusedWindow(window);
5886 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5887
5888 // With the flag set, window should not get any input
5889 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5890 mDispatcher->notifyKey(&keyArgs);
5891 window->assertNoEvents();
5892
5893 NotifyMotionArgs motionArgs =
5894 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5895 ADISPLAY_ID_DEFAULT);
5896 mDispatcher->notifyMotion(&motionArgs);
5897 window->assertNoEvents();
5898
5899 // When the window is no longer obscured because it went on top, it should get input
5900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
5901
5902 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5903 mDispatcher->notifyKey(&keyArgs);
5904 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5905
5906 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5907 ADISPLAY_ID_DEFAULT);
5908 mDispatcher->notifyMotion(&motionArgs);
5909 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5910 window->assertNoEvents();
5911}
5912
Antonio Kantekf16f2832021-09-28 04:39:20 +00005913class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
5914protected:
5915 std::shared_ptr<FakeApplicationHandle> mApp;
5916 sp<FakeWindowHandle> mWindow;
5917 sp<FakeWindowHandle> mSecondWindow;
5918
5919 void SetUp() override {
5920 InputDispatcherTest::SetUp();
5921
5922 mApp = std::make_shared<FakeApplicationHandle>();
5923 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5924 mWindow->setFocusable(true);
5925 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5926 mSecondWindow->setFocusable(true);
5927
5928 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5929 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5930
5931 setFocusedWindow(mWindow);
5932 mWindow->consumeFocusEvent(true);
5933 }
5934
5935 void changeAndVerifyTouchMode(bool inTouchMode) {
5936 mDispatcher->setInTouchMode(inTouchMode);
5937 mWindow->consumeTouchModeEvent(inTouchMode);
5938 mSecondWindow->consumeTouchModeEvent(inTouchMode);
5939 }
5940};
5941
5942TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
5943 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
5944}
5945
5946TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
5947 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
5948 mWindow->assertNoEvents();
5949 mSecondWindow->assertNoEvents();
5950}
5951
Garfield Tane84e6f92019-08-29 17:28:41 -07005952} // namespace android::inputdispatcher