blob: 84e427673ec8a2638e6c0efefa54f6baf6f8cbcd [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;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700458 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000460 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700462 mDispatcher = std::make_unique<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();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700471 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 }
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 }
arthurhungb89ccb02020-12-30 16:19:01 +0800820 case AINPUT_EVENT_TYPE_DRAG: {
821 FAIL() << "Use 'consumeDragEvent' for DRAG events";
822 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800823 default: {
824 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
825 }
826 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800827 }
828
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100829 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
830 InputEvent* event = consume();
831 ASSERT_NE(nullptr, event) << mName.c_str()
832 << ": consumer should have returned non-NULL event.";
833 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
834 << "Got " << inputEventTypeToString(event->getType())
835 << " event instead of FOCUS event";
836
837 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
838 << mName.c_str() << ": event displayId should always be NONE.";
839
840 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
841 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
842 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
843 }
844
Prabir Pradhan99987712020-11-10 18:43:05 -0800845 void consumeCaptureEvent(bool hasCapture) {
846 const InputEvent* event = consume();
847 ASSERT_NE(nullptr, event) << mName.c_str()
848 << ": consumer should have returned non-NULL event.";
849 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
850 << "Got " << inputEventTypeToString(event->getType())
851 << " event instead of CAPTURE event";
852
853 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
854 << mName.c_str() << ": event displayId should always be NONE.";
855
856 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
857 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
858 }
859
arthurhungb89ccb02020-12-30 16:19:01 +0800860 void consumeDragEvent(bool isExiting, float x, float y) {
861 const InputEvent* event = consume();
862 ASSERT_NE(nullptr, event) << mName.c_str()
863 << ": consumer should have returned non-NULL event.";
864 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
865 << "Got " << inputEventTypeToString(event->getType())
866 << " event instead of DRAG event";
867
868 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
869 << mName.c_str() << ": event displayId should always be NONE.";
870
871 const auto& dragEvent = static_cast<const DragEvent&>(*event);
872 EXPECT_EQ(isExiting, dragEvent.isExiting());
873 EXPECT_EQ(x, dragEvent.getX());
874 EXPECT_EQ(y, dragEvent.getY());
875 }
876
chaviwd1c23182019-12-20 18:44:56 -0800877 void assertNoEvents() {
878 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700879 if (event == nullptr) {
880 return;
881 }
882 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
883 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
884 ADD_FAILURE() << "Received key event "
885 << KeyEvent::actionToString(keyEvent.getAction());
886 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
887 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
888 ADD_FAILURE() << "Received motion event "
889 << MotionEvent::actionToString(motionEvent.getAction());
890 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
891 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
892 ADD_FAILURE() << "Received focus event, hasFocus = "
893 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800894 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
895 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
896 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
897 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 }
899 FAIL() << mName.c_str()
900 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800901 }
902
903 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
904
905protected:
906 std::unique_ptr<InputConsumer> mConsumer;
907 PreallocatedInputEventFactory mEventFactory;
908
909 std::string mName;
910};
911
chaviw3277faf2021-05-19 16:45:23 -0500912class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800913public:
914 static const int32_t WIDTH = 600;
915 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800916
Chris Yea209fde2020-07-22 13:54:51 -0700917 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700918 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500919 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800920 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500921 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700922 base::Result<std::unique_ptr<InputChannel>> channel =
923 dispatcher->createInputChannel(name);
924 token = (*channel)->getConnectionToken();
925 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800926 }
927
928 inputApplicationHandle->updateInfo();
929 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
930
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500931 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700932 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800933 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500934 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500935 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000936 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800937 mInfo.frameLeft = 0;
938 mInfo.frameTop = 0;
939 mInfo.frameRight = WIDTH;
940 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700941 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800942 mInfo.globalScaleFactor = 1.0;
943 mInfo.touchableRegion.clear();
944 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
945 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700946 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800947 mInfo.hasWallpaper = false;
948 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800949 mInfo.ownerPid = INJECTOR_PID;
950 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800951 mInfo.displayId = displayId;
952 }
953
Arthur Hungabbb9d82021-09-01 14:52:30 +0000954 sp<FakeWindowHandle> clone(
955 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700956 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +0000957 sp<FakeWindowHandle> handle =
958 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
959 displayId, mInfo.token);
960 return handle;
961 }
962
Vishnu Nair47074b82020-08-14 11:54:47 -0700963 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800964
Vishnu Nair958da932020-08-21 17:12:37 -0700965 void setVisible(bool visible) { mInfo.visible = visible; }
966
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700967 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500968 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700969 }
970
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700971 void setPaused(bool paused) { mInfo.paused = paused; }
972
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000973 void setAlpha(float alpha) { mInfo.alpha = alpha; }
974
chaviw3277faf2021-05-19 16:45:23 -0500975 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000976
Bernardo Rufino7393d172021-02-26 13:56:11 +0000977 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
978
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -0700979 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -0800980 mInfo.frameLeft = frame.left;
981 mInfo.frameTop = frame.top;
982 mInfo.frameRight = frame.right;
983 mInfo.frameBottom = frame.bottom;
984 mInfo.touchableRegion.clear();
985 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -0700986
987 const Rect logicalDisplayFrame = displayTransform.transform(frame);
988 ui::Transform translate;
989 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
990 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -0800991 }
992
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000993 void setType(WindowInfo::Type type) { mInfo.type = type; }
994
995 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
996
chaviw3277faf2021-05-19 16:45:23 -0500997 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000998
chaviw3277faf2021-05-19 16:45:23 -0500999 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001000
chaviw3277faf2021-05-19 16:45:23 -05001001 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001002
chaviw9eaa22c2020-07-01 16:21:27 -07001003 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1004 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1005 }
1006
1007 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001008
yunho.shinf4a80b82020-11-16 21:13:57 +09001009 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1010
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001011 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1012 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1013 expectedFlags);
1014 }
1015
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001016 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1017 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1018 }
1019
Svet Ganov5d3bc372020-01-26 23:11:07 -08001020 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001021 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001022 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1023 expectedFlags);
1024 }
1025
1026 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001027 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001028 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1029 expectedFlags);
1030 }
1031
1032 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001033 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001034 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1035 }
1036
1037 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1038 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001039 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1040 expectedFlags);
1041 }
1042
Svet Ganov5d3bc372020-01-26 23:11:07 -08001043 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001044 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1045 int32_t expectedFlags = 0) {
1046 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1047 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001048 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1049 }
1050
1051 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001052 int32_t expectedFlags = 0) {
1053 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1054 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001055 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1056 }
1057
1058 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001059 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001060 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1061 expectedFlags);
1062 }
1063
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001064 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1065 int32_t expectedFlags = 0) {
1066 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1067 expectedFlags);
1068 }
1069
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001070 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1071 ASSERT_NE(mInputReceiver, nullptr)
1072 << "Cannot consume events from a window with no receiver";
1073 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1074 }
1075
Prabir Pradhan99987712020-11-10 18:43:05 -08001076 void consumeCaptureEvent(bool hasCapture) {
1077 ASSERT_NE(mInputReceiver, nullptr)
1078 << "Cannot consume events from a window with no receiver";
1079 mInputReceiver->consumeCaptureEvent(hasCapture);
1080 }
1081
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001082 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1083 std::optional<int32_t> expectedDisplayId,
1084 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001085 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1086 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1087 expectedFlags);
1088 }
1089
arthurhungb89ccb02020-12-30 16:19:01 +08001090 void consumeDragEvent(bool isExiting, float x, float y) {
1091 mInputReceiver->consumeDragEvent(isExiting, x, y);
1092 }
1093
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001094 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001095 if (mInputReceiver == nullptr) {
1096 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1097 return std::nullopt;
1098 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001099 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001100 }
1101
1102 void finishEvent(uint32_t sequenceNum) {
1103 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1104 mInputReceiver->finishEvent(sequenceNum);
1105 }
1106
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001107 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1108 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1109 mInputReceiver->sendTimeline(inputEventId, timeline);
1110 }
1111
chaviwaf87b3e2019-10-01 16:59:28 -07001112 InputEvent* consume() {
1113 if (mInputReceiver == nullptr) {
1114 return nullptr;
1115 }
1116 return mInputReceiver->consume();
1117 }
1118
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001119 MotionEvent* consumeMotion() {
1120 InputEvent* event = consume();
1121 if (event == nullptr) {
1122 ADD_FAILURE() << "Consume failed : no event";
1123 return nullptr;
1124 }
1125 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1126 ADD_FAILURE() << "Instead of motion event, got "
1127 << inputEventTypeToString(event->getType());
1128 return nullptr;
1129 }
1130 return static_cast<MotionEvent*>(event);
1131 }
1132
Arthur Hungb92218b2018-08-14 12:00:21 +08001133 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001134 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001135 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001136 return; // Can't receive events if the window does not have input channel
1137 }
1138 ASSERT_NE(nullptr, mInputReceiver)
1139 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001140 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001141 }
1142
chaviwaf87b3e2019-10-01 16:59:28 -07001143 sp<IBinder> getToken() { return mInfo.token; }
1144
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001145 const std::string& getName() { return mName; }
1146
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001147 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1148 mInfo.ownerPid = ownerPid;
1149 mInfo.ownerUid = ownerUid;
1150 }
1151
chaviwd1c23182019-12-20 18:44:56 -08001152private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001153 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001154 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001155 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001156};
1157
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001158std::atomic<int32_t> FakeWindowHandle::sId{1};
1159
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001160static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001161 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001162 int32_t displayId = ADISPLAY_ID_NONE,
1163 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001164 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1165 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001166 KeyEvent event;
1167 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1168
1169 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001170 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001171 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1172 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001173
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001174 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1175 if (!allowKeyRepeat) {
1176 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1177 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001178 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001179 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001180 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001181}
1182
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001183static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001184 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001185 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1186}
1187
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001188// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1189// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1190// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001191static InputEventInjectionResult injectKeyDownNoRepeat(
1192 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001193 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1194 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1195 /* allowKeyRepeat */ false);
1196}
1197
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001198static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001199 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001200 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1201}
1202
Garfield Tandf26e862020-07-01 20:18:19 -07001203class PointerBuilder {
1204public:
1205 PointerBuilder(int32_t id, int32_t toolType) {
1206 mProperties.clear();
1207 mProperties.id = id;
1208 mProperties.toolType = toolType;
1209 mCoords.clear();
1210 }
1211
1212 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1213
1214 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1215
1216 PointerBuilder& axis(int32_t axis, float value) {
1217 mCoords.setAxisValue(axis, value);
1218 return *this;
1219 }
1220
1221 PointerProperties buildProperties() const { return mProperties; }
1222
1223 PointerCoords buildCoords() const { return mCoords; }
1224
1225private:
1226 PointerProperties mProperties;
1227 PointerCoords mCoords;
1228};
1229
1230class MotionEventBuilder {
1231public:
1232 MotionEventBuilder(int32_t action, int32_t source) {
1233 mAction = action;
1234 mSource = source;
1235 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1236 }
1237
1238 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1239 mEventTime = eventTime;
1240 return *this;
1241 }
1242
1243 MotionEventBuilder& displayId(int32_t displayId) {
1244 mDisplayId = displayId;
1245 return *this;
1246 }
1247
1248 MotionEventBuilder& actionButton(int32_t actionButton) {
1249 mActionButton = actionButton;
1250 return *this;
1251 }
1252
arthurhung6d4bed92021-03-17 11:59:33 +08001253 MotionEventBuilder& buttonState(int32_t buttonState) {
1254 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001255 return *this;
1256 }
1257
1258 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1259 mRawXCursorPosition = rawXCursorPosition;
1260 return *this;
1261 }
1262
1263 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1264 mRawYCursorPosition = rawYCursorPosition;
1265 return *this;
1266 }
1267
1268 MotionEventBuilder& pointer(PointerBuilder pointer) {
1269 mPointers.push_back(pointer);
1270 return *this;
1271 }
1272
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001273 MotionEventBuilder& addFlag(uint32_t flags) {
1274 mFlags |= flags;
1275 return *this;
1276 }
1277
Garfield Tandf26e862020-07-01 20:18:19 -07001278 MotionEvent build() {
1279 std::vector<PointerProperties> pointerProperties;
1280 std::vector<PointerCoords> pointerCoords;
1281 for (const PointerBuilder& pointer : mPointers) {
1282 pointerProperties.push_back(pointer.buildProperties());
1283 pointerCoords.push_back(pointer.buildCoords());
1284 }
1285
1286 // Set mouse cursor position for the most common cases to avoid boilerplate.
1287 if (mSource == AINPUT_SOURCE_MOUSE &&
1288 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1289 mPointers.size() == 1) {
1290 mRawXCursorPosition = pointerCoords[0].getX();
1291 mRawYCursorPosition = pointerCoords[0].getY();
1292 }
1293
1294 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001295 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001296 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001297 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001298 mButtonState, MotionClassification::NONE, identityTransform,
1299 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001300 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1301 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001302
1303 return event;
1304 }
1305
1306private:
1307 int32_t mAction;
1308 int32_t mSource;
1309 nsecs_t mEventTime;
1310 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1311 int32_t mActionButton{0};
1312 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001313 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001314 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1315 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1316
1317 std::vector<PointerBuilder> mPointers;
1318};
1319
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001320static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001321 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001322 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001323 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001324 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1325 injectionTimeout,
1326 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1327}
1328
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001329static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001330 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1331 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001332 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001333 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1334 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001335 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001336 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001337 MotionEvent event = MotionEventBuilder(action, source)
1338 .displayId(displayId)
1339 .eventTime(eventTime)
1340 .rawXCursorPosition(cursorPosition.x)
1341 .rawYCursorPosition(cursorPosition.y)
1342 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1343 .x(position.x)
1344 .y(position.y))
1345 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001346
1347 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001348 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001349}
1350
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001351static InputEventInjectionResult injectMotionDown(
1352 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1353 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001354 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001355}
1356
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001357static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001358 int32_t source, int32_t displayId,
1359 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001360 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001361}
1362
Jackal Guof9696682018-10-05 12:23:23 +08001363static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1364 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1365 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001366 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1367 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1368 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001369
1370 return args;
1371}
1372
chaviwd1c23182019-12-20 18:44:56 -08001373static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1374 const std::vector<PointF>& points) {
1375 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001376 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1377 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1378 }
1379
chaviwd1c23182019-12-20 18:44:56 -08001380 PointerProperties pointerProperties[pointerCount];
1381 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001382
chaviwd1c23182019-12-20 18:44:56 -08001383 for (size_t i = 0; i < pointerCount; i++) {
1384 pointerProperties[i].clear();
1385 pointerProperties[i].id = i;
1386 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001387
chaviwd1c23182019-12-20 18:44:56 -08001388 pointerCoords[i].clear();
1389 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1390 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1391 }
Jackal Guof9696682018-10-05 12:23:23 +08001392
1393 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1394 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001395 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001396 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1397 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001398 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1399 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001400 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1401 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001402
1403 return args;
1404}
1405
chaviwd1c23182019-12-20 18:44:56 -08001406static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1407 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1408}
1409
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001410static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1411 const PointerCaptureRequest& request) {
1412 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001413}
1414
Arthur Hungb92218b2018-08-14 12:00:21 +08001415TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001416 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001417 sp<FakeWindowHandle> window =
1418 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001419
Arthur Hung72d8dc32020-03-28 00:48:39 +00001420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1422 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1423 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001424
1425 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001426 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001427}
1428
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001429TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1430 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1431 sp<FakeWindowHandle> window =
1432 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1433
1434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1435 // Inject a MotionEvent to an unknown display.
1436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1437 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1438 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1439
1440 // Window should receive motion event.
1441 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1442}
1443
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001444/**
1445 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1446 * To ensure that window receives only events that were directly inside of it, add
1447 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1448 * when finding touched windows.
1449 * This test serves as a sanity check for the next test, where setInputWindows is
1450 * called twice.
1451 */
1452TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001453 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001454 sp<FakeWindowHandle> window =
1455 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1456 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001457 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001458
1459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001461 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1462 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001464
1465 // Window should receive motion event.
1466 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1467}
1468
1469/**
1470 * Calling setInputWindows twice, with the same info, should not cause any issues.
1471 * To ensure that window receives only events that were directly inside of it, add
1472 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1473 * when finding touched windows.
1474 */
1475TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001476 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001477 sp<FakeWindowHandle> window =
1478 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1479 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001480 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001481
1482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1483 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1486 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001488
1489 // Window should receive motion event.
1490 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1491}
1492
Arthur Hungb92218b2018-08-14 12:00:21 +08001493// The foreground window should receive the first touch down event.
1494TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001495 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001496 sp<FakeWindowHandle> windowTop =
1497 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1498 sp<FakeWindowHandle> windowSecond =
1499 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001500
Arthur Hung72d8dc32020-03-28 00:48:39 +00001501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1503 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1504 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001505
1506 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001507 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001508 windowSecond->assertNoEvents();
1509}
1510
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001511/**
1512 * Two windows: A top window, and a wallpaper behind the window.
1513 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1514 * gets ACTION_CANCEL.
1515 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1516 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1517 */
1518TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1519 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1520 sp<FakeWindowHandle> foregroundWindow =
1521 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1522 foregroundWindow->setHasWallpaper(true);
1523 sp<FakeWindowHandle> wallpaperWindow =
1524 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1525 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1526 constexpr int expectedWallpaperFlags =
1527 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1528
1529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1531 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1532 {100, 200}))
1533 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1534
1535 // Both foreground window and its wallpaper should receive the touch down
1536 foregroundWindow->consumeMotionDown();
1537 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1538
1539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1540 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1541 ADISPLAY_ID_DEFAULT, {110, 200}))
1542 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1543
1544 foregroundWindow->consumeMotionMove();
1545 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1546
1547 // Now the foreground window goes away, but the wallpaper stays
1548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1549 foregroundWindow->consumeMotionCancel();
1550 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1551 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1552}
1553
1554/**
1555 * A single window that receives touch (on top), and a wallpaper window underneath it.
1556 * The top window gets a multitouch gesture.
1557 * Ensure that wallpaper gets the same gesture.
1558 */
1559TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1561 sp<FakeWindowHandle> window =
1562 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1563 window->setHasWallpaper(true);
1564
1565 sp<FakeWindowHandle> wallpaperWindow =
1566 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1567 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1568 constexpr int expectedWallpaperFlags =
1569 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1570
1571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1572
1573 // Touch down on top window
1574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1575 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1576 {100, 100}))
1577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1578
1579 // Both top window and its wallpaper should receive the touch down
1580 window->consumeMotionDown();
1581 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1582
1583 // Second finger down on the top window
1584 const MotionEvent secondFingerDownEvent =
1585 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1586 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1587 AINPUT_SOURCE_TOUCHSCREEN)
1588 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1589 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1590 .x(100)
1591 .y(100))
1592 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1593 .x(150)
1594 .y(150))
1595 .build();
1596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1597 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1598 InputEventInjectionSync::WAIT_FOR_RESULT))
1599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1600
1601 window->consumeMotionPointerDown(1 /* pointerIndex */);
1602 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1603 expectedWallpaperFlags);
1604 window->assertNoEvents();
1605 wallpaperWindow->assertNoEvents();
1606}
1607
1608/**
1609 * Two windows: a window on the left and window on the right.
1610 * A third window, wallpaper, is behind both windows, and spans both top windows.
1611 * The first touch down goes to the left window. A second pointer touches down on the right window.
1612 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1613 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1614 * ACTION_POINTER_DOWN(1).
1615 */
1616TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1617 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1618 sp<FakeWindowHandle> leftWindow =
1619 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1620 leftWindow->setFrame(Rect(0, 0, 200, 200));
1621 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1622 leftWindow->setHasWallpaper(true);
1623
1624 sp<FakeWindowHandle> rightWindow =
1625 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1626 rightWindow->setFrame(Rect(200, 0, 400, 200));
1627 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1628 rightWindow->setHasWallpaper(true);
1629
1630 sp<FakeWindowHandle> wallpaperWindow =
1631 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1632 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1633 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1634 constexpr int expectedWallpaperFlags =
1635 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1636
1637 mDispatcher->setInputWindows(
1638 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1639
1640 // Touch down on left window
1641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1642 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1643 {100, 100}))
1644 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1645
1646 // Both foreground window and its wallpaper should receive the touch down
1647 leftWindow->consumeMotionDown();
1648 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1649
1650 // Second finger down on the right window
1651 const MotionEvent secondFingerDownEvent =
1652 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1653 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1654 AINPUT_SOURCE_TOUCHSCREEN)
1655 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1656 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1657 .x(100)
1658 .y(100))
1659 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1660 .x(300)
1661 .y(100))
1662 .build();
1663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1664 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1665 InputEventInjectionSync::WAIT_FOR_RESULT))
1666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1667
1668 leftWindow->consumeMotionMove();
1669 // Since the touch is split, right window gets ACTION_DOWN
1670 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1671 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1672 expectedWallpaperFlags);
1673
1674 // Now, leftWindow, which received the first finger, disappears.
1675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1676 leftWindow->consumeMotionCancel();
1677 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1678 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1679
1680 // The pointer that's still down on the right window moves, and goes to the right window only.
1681 // As far as the dispatcher's concerned though, both pointers are still present.
1682 const MotionEvent secondFingerMoveEvent =
1683 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1684 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1685 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1686 .x(100)
1687 .y(100))
1688 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1689 .x(310)
1690 .y(110))
1691 .build();
1692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1693 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1694 InputEventInjectionSync::WAIT_FOR_RESULT));
1695 rightWindow->consumeMotionMove();
1696
1697 leftWindow->assertNoEvents();
1698 rightWindow->assertNoEvents();
1699 wallpaperWindow->assertNoEvents();
1700}
1701
Garfield Tandf26e862020-07-01 20:18:19 -07001702TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001703 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001704 sp<FakeWindowHandle> windowLeft =
1705 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1706 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001707 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001708 sp<FakeWindowHandle> windowRight =
1709 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1710 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001711 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001712
1713 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1714
1715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1716
1717 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001719 injectMotionEvent(mDispatcher,
1720 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1721 AINPUT_SOURCE_MOUSE)
1722 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1723 .x(900)
1724 .y(400))
1725 .build()));
1726 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1727 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1728 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1729 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1730
1731 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001733 injectMotionEvent(mDispatcher,
1734 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1735 AINPUT_SOURCE_MOUSE)
1736 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1737 .x(300)
1738 .y(400))
1739 .build()));
1740 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1741 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1742 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1743 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1744 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1745 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1746
1747 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001749 injectMotionEvent(mDispatcher,
1750 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1751 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1752 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1753 .x(300)
1754 .y(400))
1755 .build()));
1756 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1757
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001758 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001759 injectMotionEvent(mDispatcher,
1760 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1761 AINPUT_SOURCE_MOUSE)
1762 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1763 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1764 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1765 .x(300)
1766 .y(400))
1767 .build()));
1768 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1769 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1770
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001772 injectMotionEvent(mDispatcher,
1773 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1774 AINPUT_SOURCE_MOUSE)
1775 .buttonState(0)
1776 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1777 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1778 .x(300)
1779 .y(400))
1780 .build()));
1781 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1782 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1783
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001785 injectMotionEvent(mDispatcher,
1786 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1787 .buttonState(0)
1788 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1789 .x(300)
1790 .y(400))
1791 .build()));
1792 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1793
1794 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001796 injectMotionEvent(mDispatcher,
1797 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1798 AINPUT_SOURCE_MOUSE)
1799 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1800 .x(900)
1801 .y(400))
1802 .build()));
1803 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1804 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1805 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1806 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1807 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1808 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1809}
1810
1811// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1812// directly in this test.
1813TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001815 sp<FakeWindowHandle> window =
1816 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1817 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001818 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001819
1820 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1821
1822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1823
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001825 injectMotionEvent(mDispatcher,
1826 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1827 AINPUT_SOURCE_MOUSE)
1828 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1829 .x(300)
1830 .y(400))
1831 .build()));
1832 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1833 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1834
1835 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001837 injectMotionEvent(mDispatcher,
1838 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1839 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1840 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1841 .x(300)
1842 .y(400))
1843 .build()));
1844 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1845
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001847 injectMotionEvent(mDispatcher,
1848 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1849 AINPUT_SOURCE_MOUSE)
1850 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1851 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1852 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1853 .x(300)
1854 .y(400))
1855 .build()));
1856 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1857 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1858
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001860 injectMotionEvent(mDispatcher,
1861 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1862 AINPUT_SOURCE_MOUSE)
1863 .buttonState(0)
1864 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1865 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1866 .x(300)
1867 .y(400))
1868 .build()));
1869 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1870 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1871
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001873 injectMotionEvent(mDispatcher,
1874 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1875 .buttonState(0)
1876 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1877 .x(300)
1878 .y(400))
1879 .build()));
1880 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1881
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001883 injectMotionEvent(mDispatcher,
1884 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1885 AINPUT_SOURCE_MOUSE)
1886 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1887 .x(300)
1888 .y(400))
1889 .build()));
1890 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1891 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1892}
1893
Garfield Tan00f511d2019-06-12 16:55:40 -07001894TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001895 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001896
1897 sp<FakeWindowHandle> windowLeft =
1898 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1899 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001900 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001901 sp<FakeWindowHandle> windowRight =
1902 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1903 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001904 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001905
1906 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1907
Arthur Hung72d8dc32020-03-28 00:48:39 +00001908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001909
1910 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1911 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001913 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001914 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001915 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001916 windowRight->assertNoEvents();
1917}
1918
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001919TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001920 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001921 sp<FakeWindowHandle> window =
1922 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001923 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001924
Arthur Hung72d8dc32020-03-28 00:48:39 +00001925 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001926 setFocusedWindow(window);
1927
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001928 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001929
1930 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1931 mDispatcher->notifyKey(&keyArgs);
1932
1933 // Window should receive key down event.
1934 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1935
1936 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1937 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001938 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001939 mDispatcher->notifyDeviceReset(&args);
1940 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1941 AKEY_EVENT_FLAG_CANCELED);
1942}
1943
1944TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001945 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001946 sp<FakeWindowHandle> window =
1947 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1948
Arthur Hung72d8dc32020-03-28 00:48:39 +00001949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001950
1951 NotifyMotionArgs motionArgs =
1952 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1953 ADISPLAY_ID_DEFAULT);
1954 mDispatcher->notifyMotion(&motionArgs);
1955
1956 // Window should receive motion down event.
1957 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1958
1959 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1960 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001961 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001962 mDispatcher->notifyDeviceReset(&args);
1963 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1964 0 /*expectedFlags*/);
1965}
1966
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001967/**
1968 * Ensure the correct coordinate spaces are used by InputDispatcher.
1969 *
1970 * InputDispatcher works in the display space, so its coordinate system is relative to the display
1971 * panel. Windows get events in the window space, and get raw coordinates in the logical display
1972 * space.
1973 */
1974class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
1975public:
1976 void SetUp() override {
1977 InputDispatcherTest::SetUp();
1978 mDisplayInfos.clear();
1979 mWindowInfos.clear();
1980 }
1981
1982 void addDisplayInfo(int displayId, const ui::Transform& transform) {
1983 gui::DisplayInfo info;
1984 info.displayId = displayId;
1985 info.transform = transform;
1986 mDisplayInfos.push_back(std::move(info));
1987 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
1988 }
1989
1990 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
1991 mWindowInfos.push_back(*windowHandle->getInfo());
1992 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
1993 }
1994
1995 // Set up a test scenario where the display has a scaled projection and there are two windows
1996 // on the display.
1997 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
1998 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
1999 // respectively.
2000 ui::Transform displayTransform;
2001 displayTransform.set(2, 0, 0, 4);
2002 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2003
2004 std::shared_ptr<FakeApplicationHandle> application =
2005 std::make_shared<FakeApplicationHandle>();
2006
2007 // Add two windows to the display. Their frames are represented in the display space.
2008 sp<FakeWindowHandle> firstWindow =
2009 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2010 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2011 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2012 addWindow(firstWindow);
2013
2014 sp<FakeWindowHandle> secondWindow =
2015 new FakeWindowHandle(application, mDispatcher, "Second Window",
2016 ADISPLAY_ID_DEFAULT);
2017 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2018 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2019 addWindow(secondWindow);
2020 return {std::move(firstWindow), std::move(secondWindow)};
2021 }
2022
2023private:
2024 std::vector<gui::DisplayInfo> mDisplayInfos;
2025 std::vector<gui::WindowInfo> mWindowInfos;
2026};
2027
2028TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2029 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2030 // Send down to the first window. The point is represented in the display space. The point is
2031 // selected so that if the hit test was done with the transform applied to it, then it would
2032 // end up in the incorrect window.
2033 NotifyMotionArgs downMotionArgs =
2034 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2035 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2036 mDispatcher->notifyMotion(&downMotionArgs);
2037
2038 firstWindow->consumeMotionDown();
2039 secondWindow->assertNoEvents();
2040}
2041
2042// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2043// the event should be treated as being in the logical display space.
2044TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2045 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2046 // Send down to the first window. The point is represented in the logical display space. The
2047 // point is selected so that if the hit test was done in logical display space, then it would
2048 // end up in the incorrect window.
2049 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2050 PointF{75 * 2, 55 * 4});
2051
2052 firstWindow->consumeMotionDown();
2053 secondWindow->assertNoEvents();
2054}
2055
2056TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2057 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2058
2059 // Send down to the second window.
2060 NotifyMotionArgs downMotionArgs =
2061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2062 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2063 mDispatcher->notifyMotion(&downMotionArgs);
2064
2065 firstWindow->assertNoEvents();
2066 const MotionEvent* event = secondWindow->consumeMotion();
2067 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2068
2069 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2070 EXPECT_EQ(300, event->getRawX(0));
2071 EXPECT_EQ(880, event->getRawY(0));
2072
2073 // Ensure that the x and y values are in the window's coordinate space.
2074 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2075 // the logical display space. This will be the origin of the window space.
2076 EXPECT_EQ(100, event->getX(0));
2077 EXPECT_EQ(80, event->getY(0));
2078}
2079
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002080using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2081 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002082
2083class TransferTouchFixture : public InputDispatcherTest,
2084 public ::testing::WithParamInterface<TransferFunction> {};
2085
2086TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002087 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002088
2089 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002090 sp<FakeWindowHandle> firstWindow =
2091 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2092 sp<FakeWindowHandle> secondWindow =
2093 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002094
2095 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002097
2098 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002099 NotifyMotionArgs downMotionArgs =
2100 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2101 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002102 mDispatcher->notifyMotion(&downMotionArgs);
2103 // Only the first window should get the down event
2104 firstWindow->consumeMotionDown();
2105 secondWindow->assertNoEvents();
2106
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002107 // Transfer touch to the second window
2108 TransferFunction f = GetParam();
2109 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2110 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002111 // The first window gets cancel and the second gets down
2112 firstWindow->consumeMotionCancel();
2113 secondWindow->consumeMotionDown();
2114
2115 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002116 NotifyMotionArgs upMotionArgs =
2117 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2118 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002119 mDispatcher->notifyMotion(&upMotionArgs);
2120 // The first window gets no events and the second gets up
2121 firstWindow->assertNoEvents();
2122 secondWindow->consumeMotionUp();
2123}
2124
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002125TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002126 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002127
2128 PointF touchPoint = {10, 10};
2129
2130 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002131 sp<FakeWindowHandle> firstWindow =
2132 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2133 sp<FakeWindowHandle> secondWindow =
2134 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002135
2136 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002138
2139 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002140 NotifyMotionArgs downMotionArgs =
2141 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2142 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002143 mDispatcher->notifyMotion(&downMotionArgs);
2144 // Only the first window should get the down event
2145 firstWindow->consumeMotionDown();
2146 secondWindow->assertNoEvents();
2147
2148 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002149 NotifyMotionArgs pointerDownMotionArgs =
2150 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2151 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2152 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2153 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002154 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2155 // Only the first window should get the pointer down event
2156 firstWindow->consumeMotionPointerDown(1);
2157 secondWindow->assertNoEvents();
2158
2159 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002160 TransferFunction f = GetParam();
2161 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2162 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002163 // The first window gets cancel and the second gets down and pointer down
2164 firstWindow->consumeMotionCancel();
2165 secondWindow->consumeMotionDown();
2166 secondWindow->consumeMotionPointerDown(1);
2167
2168 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002169 NotifyMotionArgs pointerUpMotionArgs =
2170 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2171 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2172 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2173 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002174 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2175 // The first window gets nothing and the second gets pointer up
2176 firstWindow->assertNoEvents();
2177 secondWindow->consumeMotionPointerUp(1);
2178
2179 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002180 NotifyMotionArgs upMotionArgs =
2181 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2182 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002183 mDispatcher->notifyMotion(&upMotionArgs);
2184 // The first window gets nothing and the second gets up
2185 firstWindow->assertNoEvents();
2186 secondWindow->consumeMotionUp();
2187}
2188
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002189// For the cases of single pointer touch and two pointers non-split touch, the api's
2190// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2191// for the case where there are multiple pointers split across several windows.
2192INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2193 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002194 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2195 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002196 return dispatcher->transferTouch(destChannelToken);
2197 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002198 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2199 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002200 return dispatcher->transferTouchFocus(from, to,
2201 false /*isDragAndDrop*/);
2202 }));
2203
Svet Ganov5d3bc372020-01-26 23:11:07 -08002204TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002205 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002206
2207 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002208 sp<FakeWindowHandle> firstWindow =
2209 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002210 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002211 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002212
2213 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002214 sp<FakeWindowHandle> secondWindow =
2215 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002216 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002217 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002218
2219 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002220 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002221
2222 PointF pointInFirst = {300, 200};
2223 PointF pointInSecond = {300, 600};
2224
2225 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002226 NotifyMotionArgs firstDownMotionArgs =
2227 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2228 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002229 mDispatcher->notifyMotion(&firstDownMotionArgs);
2230 // Only the first window should get the down event
2231 firstWindow->consumeMotionDown();
2232 secondWindow->assertNoEvents();
2233
2234 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002235 NotifyMotionArgs secondDownMotionArgs =
2236 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2237 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2238 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2239 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002240 mDispatcher->notifyMotion(&secondDownMotionArgs);
2241 // The first window gets a move and the second a down
2242 firstWindow->consumeMotionMove();
2243 secondWindow->consumeMotionDown();
2244
2245 // Transfer touch focus to the second window
2246 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2247 // The first window gets cancel and the new gets pointer down (it already saw down)
2248 firstWindow->consumeMotionCancel();
2249 secondWindow->consumeMotionPointerDown(1);
2250
2251 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002252 NotifyMotionArgs pointerUpMotionArgs =
2253 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2254 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2255 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2256 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002257 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2258 // The first window gets nothing and the second gets pointer up
2259 firstWindow->assertNoEvents();
2260 secondWindow->consumeMotionPointerUp(1);
2261
2262 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002263 NotifyMotionArgs upMotionArgs =
2264 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2265 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266 mDispatcher->notifyMotion(&upMotionArgs);
2267 // The first window gets nothing and the second gets up
2268 firstWindow->assertNoEvents();
2269 secondWindow->consumeMotionUp();
2270}
2271
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002272// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2273// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2274// touch is not supported, so the touch should continue on those windows and the transferred-to
2275// window should get nothing.
2276TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2277 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2278
2279 // Create a non touch modal window that supports split touch
2280 sp<FakeWindowHandle> firstWindow =
2281 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2282 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002283 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002284
2285 // Create a non touch modal window that supports split touch
2286 sp<FakeWindowHandle> secondWindow =
2287 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2288 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002289 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002290
2291 // Add the windows to the dispatcher
2292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2293
2294 PointF pointInFirst = {300, 200};
2295 PointF pointInSecond = {300, 600};
2296
2297 // Send down to the first window
2298 NotifyMotionArgs firstDownMotionArgs =
2299 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2300 ADISPLAY_ID_DEFAULT, {pointInFirst});
2301 mDispatcher->notifyMotion(&firstDownMotionArgs);
2302 // Only the first window should get the down event
2303 firstWindow->consumeMotionDown();
2304 secondWindow->assertNoEvents();
2305
2306 // Send down to the second window
2307 NotifyMotionArgs secondDownMotionArgs =
2308 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2309 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2310 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2311 {pointInFirst, pointInSecond});
2312 mDispatcher->notifyMotion(&secondDownMotionArgs);
2313 // The first window gets a move and the second a down
2314 firstWindow->consumeMotionMove();
2315 secondWindow->consumeMotionDown();
2316
2317 // Transfer touch focus to the second window
2318 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2319 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2320 ASSERT_FALSE(transferred);
2321 firstWindow->assertNoEvents();
2322 secondWindow->assertNoEvents();
2323
2324 // The rest of the dispatch should proceed as normal
2325 // Send pointer up to the second window
2326 NotifyMotionArgs pointerUpMotionArgs =
2327 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2328 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2329 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2330 {pointInFirst, pointInSecond});
2331 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2332 // The first window gets MOVE and the second gets pointer up
2333 firstWindow->consumeMotionMove();
2334 secondWindow->consumeMotionUp();
2335
2336 // Send up event to the first window
2337 NotifyMotionArgs upMotionArgs =
2338 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2339 ADISPLAY_ID_DEFAULT);
2340 mDispatcher->notifyMotion(&upMotionArgs);
2341 // The first window gets nothing and the second gets up
2342 firstWindow->consumeMotionUp();
2343 secondWindow->assertNoEvents();
2344}
2345
Arthur Hungabbb9d82021-09-01 14:52:30 +00002346// This case will create two windows and one mirrored window on the default display and mirror
2347// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2348// the windows info of second display before default display.
2349TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2350 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2351 sp<FakeWindowHandle> firstWindowInPrimary =
2352 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2353 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2354 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2355 sp<FakeWindowHandle> secondWindowInPrimary =
2356 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2357 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2358 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2359
2360 sp<FakeWindowHandle> mirrorWindowInPrimary =
2361 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2362 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2363 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2364
2365 sp<FakeWindowHandle> firstWindowInSecondary =
2366 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2367 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2368 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2369
2370 sp<FakeWindowHandle> secondWindowInSecondary =
2371 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2372 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2373 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2374
2375 // Update window info, let it find window handle of second display first.
2376 mDispatcher->setInputWindows(
2377 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2378 {ADISPLAY_ID_DEFAULT,
2379 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2380
2381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2382 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2383 {50, 50}))
2384 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2385
2386 // Window should receive motion event.
2387 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2388
2389 // Transfer touch focus
2390 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2391 secondWindowInPrimary->getToken()));
2392 // The first window gets cancel.
2393 firstWindowInPrimary->consumeMotionCancel();
2394 secondWindowInPrimary->consumeMotionDown();
2395
2396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2397 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2398 ADISPLAY_ID_DEFAULT, {150, 50}))
2399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2400 firstWindowInPrimary->assertNoEvents();
2401 secondWindowInPrimary->consumeMotionMove();
2402
2403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2404 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2405 {150, 50}))
2406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2407 firstWindowInPrimary->assertNoEvents();
2408 secondWindowInPrimary->consumeMotionUp();
2409}
2410
2411// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2412// 'transferTouch' api.
2413TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2415 sp<FakeWindowHandle> firstWindowInPrimary =
2416 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2417 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2418 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2419 sp<FakeWindowHandle> secondWindowInPrimary =
2420 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2421 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2422 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2423
2424 sp<FakeWindowHandle> mirrorWindowInPrimary =
2425 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2426 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2427 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2428
2429 sp<FakeWindowHandle> firstWindowInSecondary =
2430 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2431 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2432 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2433
2434 sp<FakeWindowHandle> secondWindowInSecondary =
2435 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2436 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2437 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2438
2439 // Update window info, let it find window handle of second display first.
2440 mDispatcher->setInputWindows(
2441 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2442 {ADISPLAY_ID_DEFAULT,
2443 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2444
2445 // Touch on second display.
2446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2447 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2448 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2449
2450 // Window should receive motion event.
2451 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2452
2453 // Transfer touch focus
2454 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2455
2456 // The first window gets cancel.
2457 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2458 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2459
2460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2461 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2462 SECOND_DISPLAY_ID, {150, 50}))
2463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2464 firstWindowInPrimary->assertNoEvents();
2465 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2466
2467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2468 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2470 firstWindowInPrimary->assertNoEvents();
2471 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2472}
2473
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002474TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002475 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002476 sp<FakeWindowHandle> window =
2477 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2478
Vishnu Nair47074b82020-08-14 11:54:47 -07002479 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002481 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002482
2483 window->consumeFocusEvent(true);
2484
2485 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2486 mDispatcher->notifyKey(&keyArgs);
2487
2488 // Window should receive key down event.
2489 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2490}
2491
2492TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002493 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002494 sp<FakeWindowHandle> window =
2495 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2496
Arthur Hung72d8dc32020-03-28 00:48:39 +00002497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002498
2499 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2500 mDispatcher->notifyKey(&keyArgs);
2501 mDispatcher->waitForIdle();
2502
2503 window->assertNoEvents();
2504}
2505
2506// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2507TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002508 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002509 sp<FakeWindowHandle> window =
2510 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2511
Arthur Hung72d8dc32020-03-28 00:48:39 +00002512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002513
2514 // Send key
2515 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2516 mDispatcher->notifyKey(&keyArgs);
2517 // Send motion
2518 NotifyMotionArgs motionArgs =
2519 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2520 ADISPLAY_ID_DEFAULT);
2521 mDispatcher->notifyMotion(&motionArgs);
2522
2523 // Window should receive only the motion event
2524 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2525 window->assertNoEvents(); // Key event or focus event will not be received
2526}
2527
arthurhungea3f4fc2020-12-21 23:18:53 +08002528TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2529 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2530
2531 // Create first non touch modal window that supports split touch
2532 sp<FakeWindowHandle> firstWindow =
2533 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2534 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002535 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002536
2537 // Create second non touch modal window that supports split touch
2538 sp<FakeWindowHandle> secondWindow =
2539 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2540 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002541 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002542
2543 // Add the windows to the dispatcher
2544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2545
2546 PointF pointInFirst = {300, 200};
2547 PointF pointInSecond = {300, 600};
2548
2549 // Send down to the first window
2550 NotifyMotionArgs firstDownMotionArgs =
2551 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2552 ADISPLAY_ID_DEFAULT, {pointInFirst});
2553 mDispatcher->notifyMotion(&firstDownMotionArgs);
2554 // Only the first window should get the down event
2555 firstWindow->consumeMotionDown();
2556 secondWindow->assertNoEvents();
2557
2558 // Send down to the second window
2559 NotifyMotionArgs secondDownMotionArgs =
2560 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2561 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2562 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2563 {pointInFirst, pointInSecond});
2564 mDispatcher->notifyMotion(&secondDownMotionArgs);
2565 // The first window gets a move and the second a down
2566 firstWindow->consumeMotionMove();
2567 secondWindow->consumeMotionDown();
2568
2569 // Send pointer cancel to the second window
2570 NotifyMotionArgs pointerUpMotionArgs =
2571 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2572 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2573 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2574 {pointInFirst, pointInSecond});
2575 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2576 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2577 // The first window gets move and the second gets cancel.
2578 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2579 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2580
2581 // Send up event.
2582 NotifyMotionArgs upMotionArgs =
2583 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2584 ADISPLAY_ID_DEFAULT);
2585 mDispatcher->notifyMotion(&upMotionArgs);
2586 // The first window gets up and the second gets nothing.
2587 firstWindow->consumeMotionUp();
2588 secondWindow->assertNoEvents();
2589}
2590
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002591TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2592 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2593
2594 sp<FakeWindowHandle> window =
2595 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2597 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2598 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2599 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2600
2601 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2602 window->assertNoEvents();
2603 mDispatcher->waitForIdle();
2604}
2605
chaviwd1c23182019-12-20 18:44:56 -08002606class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002607public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002608 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002609 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002610 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002611 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002612 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002613 }
2614
chaviwd1c23182019-12-20 18:44:56 -08002615 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2616
2617 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2618 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2619 expectedDisplayId, expectedFlags);
2620 }
2621
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002622 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2623
2624 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2625
chaviwd1c23182019-12-20 18:44:56 -08002626 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2627 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2628 expectedDisplayId, expectedFlags);
2629 }
2630
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002631 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2632 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2633 expectedDisplayId, expectedFlags);
2634 }
2635
chaviwd1c23182019-12-20 18:44:56 -08002636 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2637 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2638 expectedDisplayId, expectedFlags);
2639 }
2640
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002641 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2642 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2643 expectedDisplayId, expectedFlags);
2644 }
2645
Evan Rosky84f07f02021-04-16 10:42:42 -07002646 MotionEvent* consumeMotion() {
2647 InputEvent* event = mInputReceiver->consume();
2648 if (!event) {
2649 ADD_FAILURE() << "No event was produced";
2650 return nullptr;
2651 }
2652 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2653 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2654 return nullptr;
2655 }
2656 return static_cast<MotionEvent*>(event);
2657 }
2658
chaviwd1c23182019-12-20 18:44:56 -08002659 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2660
2661private:
2662 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002663};
2664
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002665/**
2666 * Two entities that receive touch: A window, and a global monitor.
2667 * The touch goes to the window, and then the window disappears.
2668 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2669 * for the monitor, as well.
2670 * 1. foregroundWindow
2671 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2672 */
2673TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2674 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2675 sp<FakeWindowHandle> window =
2676 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2677
2678 FakeMonitorReceiver monitor =
2679 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2680 false /*isGestureMonitor*/);
2681
2682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2684 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2685 {100, 200}))
2686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2687
2688 // Both the foreground window and the global monitor should receive the touch down
2689 window->consumeMotionDown();
2690 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2691
2692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2693 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2694 ADISPLAY_ID_DEFAULT, {110, 200}))
2695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2696
2697 window->consumeMotionMove();
2698 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2699
2700 // Now the foreground window goes away
2701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2702 window->consumeMotionCancel();
2703 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2704
2705 // If more events come in, there will be no more foreground window to send them to. This will
2706 // cause a cancel for the monitor, as well.
2707 ASSERT_EQ(InputEventInjectionResult::FAILED,
2708 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2709 ADISPLAY_ID_DEFAULT, {120, 200}))
2710 << "Injection should fail because the window was removed";
2711 window->assertNoEvents();
2712 // Global monitor now gets the cancel
2713 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2714}
2715
Michael Wright3a240c42019-12-10 20:53:41 +00002716// Tests for gesture monitors
2717TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002718 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002719 sp<FakeWindowHandle> window =
2720 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002722
chaviwd1c23182019-12-20 18:44:56 -08002723 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2724 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002727 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002728 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002729 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002730 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002731}
2732
2733TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002735 sp<FakeWindowHandle> window =
2736 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2737
2738 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002739 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002740
Arthur Hung72d8dc32020-03-28 00:48:39 +00002741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002742 setFocusedWindow(window);
2743
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002744 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002745
chaviwd1c23182019-12-20 18:44:56 -08002746 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2747 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002748
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2750 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002751 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002752 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002753}
2754
2755TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002756 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002757 sp<FakeWindowHandle> window =
2758 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002760
chaviwd1c23182019-12-20 18:44:56 -08002761 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2762 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002763
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002766 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002767 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002768 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002769
2770 window->releaseChannel();
2771
chaviwd1c23182019-12-20 18:44:56 -08002772 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002773
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002775 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002777 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002778}
2779
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002780TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2781 FakeMonitorReceiver monitor =
2782 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2783 true /*isGestureMonitor*/);
2784
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2787 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2788 ASSERT_TRUE(consumeSeq);
2789
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002790 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002791 monitor.finishEvent(*consumeSeq);
2792 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002793 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002794}
2795
Evan Rosky84f07f02021-04-16 10:42:42 -07002796// Tests for gesture monitors
2797TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2798 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2799 sp<FakeWindowHandle> window =
2800 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2802 window->setWindowOffset(20, 40);
2803 window->setWindowTransform(0, 1, -1, 0);
2804
2805 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2806 true /*isGestureMonitor*/);
2807
2808 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2809 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2811 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2812 MotionEvent* event = monitor.consumeMotion();
2813 // Even though window has transform, gesture monitor must not.
2814 ASSERT_EQ(ui::Transform(), event->getTransform());
2815}
2816
chaviw81e2bb92019-12-18 15:03:51 -08002817TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002818 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002819 sp<FakeWindowHandle> window =
2820 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2821
Arthur Hung72d8dc32020-03-28 00:48:39 +00002822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002823
2824 NotifyMotionArgs motionArgs =
2825 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2826 ADISPLAY_ID_DEFAULT);
2827
2828 mDispatcher->notifyMotion(&motionArgs);
2829 // Window should receive motion down event.
2830 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2831
2832 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002833 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002834 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2835 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2836 motionArgs.pointerCoords[0].getX() - 10);
2837
2838 mDispatcher->notifyMotion(&motionArgs);
2839 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2840 0 /*expectedFlags*/);
2841}
2842
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002843/**
2844 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2845 * the device default right away. In the test scenario, we check both the default value,
2846 * and the action of enabling / disabling.
2847 */
2848TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002849 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002850 sp<FakeWindowHandle> window =
2851 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2852
2853 // Set focused application.
2854 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002855 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002856
2857 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002859 setFocusedWindow(window);
2860
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002861 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2862
2863 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002864 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002866 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2867
2868 SCOPED_TRACE("Disable touch mode");
2869 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002870 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002872 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002873 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2874
2875 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002876 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002878 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2879
2880 SCOPED_TRACE("Enable touch mode again");
2881 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002882 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002884 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002885 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2886
2887 window->assertNoEvents();
2888}
2889
Gang Wange9087892020-01-07 12:17:14 -05002890TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002891 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002892 sp<FakeWindowHandle> window =
2893 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2894
2895 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002896 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002897
Arthur Hung72d8dc32020-03-28 00:48:39 +00002898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002899 setFocusedWindow(window);
2900
Gang Wange9087892020-01-07 12:17:14 -05002901 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2902
2903 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2904 mDispatcher->notifyKey(&keyArgs);
2905
2906 InputEvent* event = window->consume();
2907 ASSERT_NE(event, nullptr);
2908
2909 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2910 ASSERT_NE(verified, nullptr);
2911 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2912
2913 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2914 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2915 ASSERT_EQ(keyArgs.source, verified->source);
2916 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2917
2918 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2919
2920 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2921 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002922 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2923 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2924 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2925 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2926 ASSERT_EQ(0, verifiedKey.repeatCount);
2927}
2928
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002929TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002930 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002931 sp<FakeWindowHandle> window =
2932 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2933
2934 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2935
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002936 ui::Transform transform;
2937 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
2938
2939 gui::DisplayInfo displayInfo;
2940 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
2941 displayInfo.transform = transform;
2942
2943 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002944
2945 NotifyMotionArgs motionArgs =
2946 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2947 ADISPLAY_ID_DEFAULT);
2948 mDispatcher->notifyMotion(&motionArgs);
2949
2950 InputEvent* event = window->consume();
2951 ASSERT_NE(event, nullptr);
2952
2953 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2954 ASSERT_NE(verified, nullptr);
2955 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2956
2957 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2958 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2959 EXPECT_EQ(motionArgs.source, verified->source);
2960 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2961
2962 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2963
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002964 const vec2 rawXY =
2965 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
2966 motionArgs.pointerCoords[0].getXYValue());
2967 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
2968 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002969 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2970 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2971 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2972 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2973 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2974}
2975
Prabir Pradhan664834b2021-05-20 16:00:42 -07002976TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002977 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2978 sp<FakeWindowHandle> window =
2979 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2980 const std::string name = window->getName();
2981
2982 // Window gets transformed by offset values.
2983 window->setWindowOffset(500.0f, 500.0f);
2984
2985 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2986 window->setFocusable(true);
2987
2988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2989
2990 // First, we set focused window so that focusedWindowHandle is not null.
2991 setFocusedWindow(window);
2992
2993 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2994 window->consumeFocusEvent(true);
2995
Prabir Pradhan664834b2021-05-20 16:00:42 -07002996 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2997 AMOTION_EVENT_ACTION_DOWN),
2998 std::pair(AINPUT_SOURCE_JOYSTICK,
2999 AMOTION_EVENT_ACTION_MOVE)};
3000 for (const auto& [source, action] : nonTransformedSources) {
3001 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08003002 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09003003
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003004 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08003005 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09003006
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003007 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07003008 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08003009 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09003010
Prabir Pradhanbd527712021-03-09 19:17:09 -08003011 float expectedX = motionArgs.pointerCoords[0].getX();
3012 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09003013
Prabir Pradhanbd527712021-03-09 19:17:09 -08003014 // Ensure the axis values from the final motion event are not transformed.
3015 EXPECT_EQ(expectedX, motionEvent.getX(0))
3016 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
3017 << motionEvent.getX(0);
3018 EXPECT_EQ(expectedY, motionEvent.getY(0))
3019 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
3020 << motionEvent.getY(0);
3021 // Ensure the raw and transformed axis values for the motion event are the same.
3022 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
3023 << "expected raw and transformed X-axis values to be equal";
3024 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
3025 << "expected raw and transformed Y-axis values to be equal";
3026 }
yunho.shinf4a80b82020-11-16 21:13:57 +09003027}
3028
chaviw09c8d2d2020-08-24 15:48:26 -07003029/**
3030 * Ensure that separate calls to sign the same data are generating the same key.
3031 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3032 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3033 * tests.
3034 */
3035TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3036 KeyEvent event = getTestKeyEvent();
3037 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3038
3039 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3040 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3041 ASSERT_EQ(hmac1, hmac2);
3042}
3043
3044/**
3045 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3046 */
3047TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3048 KeyEvent event = getTestKeyEvent();
3049 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3050 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3051
3052 verifiedEvent.deviceId += 1;
3053 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3054
3055 verifiedEvent.source += 1;
3056 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3057
3058 verifiedEvent.eventTimeNanos += 1;
3059 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3060
3061 verifiedEvent.displayId += 1;
3062 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3063
3064 verifiedEvent.action += 1;
3065 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3066
3067 verifiedEvent.downTimeNanos += 1;
3068 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3069
3070 verifiedEvent.flags += 1;
3071 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3072
3073 verifiedEvent.keyCode += 1;
3074 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3075
3076 verifiedEvent.scanCode += 1;
3077 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3078
3079 verifiedEvent.metaState += 1;
3080 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3081
3082 verifiedEvent.repeatCount += 1;
3083 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3084}
3085
Vishnu Nair958da932020-08-21 17:12:37 -07003086TEST_F(InputDispatcherTest, SetFocusedWindow) {
3087 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3088 sp<FakeWindowHandle> windowTop =
3089 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3090 sp<FakeWindowHandle> windowSecond =
3091 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3092 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3093
3094 // Top window is also focusable but is not granted focus.
3095 windowTop->setFocusable(true);
3096 windowSecond->setFocusable(true);
3097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3098 setFocusedWindow(windowSecond);
3099
3100 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3102 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003103
3104 // Focused window should receive event.
3105 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3106 windowTop->assertNoEvents();
3107}
3108
3109TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3110 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3111 sp<FakeWindowHandle> window =
3112 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3113 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3114
3115 window->setFocusable(true);
3116 // Release channel for window is no longer valid.
3117 window->releaseChannel();
3118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3119 setFocusedWindow(window);
3120
3121 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003122 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3123 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003124
3125 // window channel is invalid, so it should not receive any input event.
3126 window->assertNoEvents();
3127}
3128
3129TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3130 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3131 sp<FakeWindowHandle> window =
3132 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3133 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3134
3135 // Window is not focusable.
3136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3137 setFocusedWindow(window);
3138
3139 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003140 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3141 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003142
3143 // window is invalid, so it should not receive any input event.
3144 window->assertNoEvents();
3145}
3146
3147TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3149 sp<FakeWindowHandle> windowTop =
3150 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3151 sp<FakeWindowHandle> windowSecond =
3152 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3153 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3154
3155 windowTop->setFocusable(true);
3156 windowSecond->setFocusable(true);
3157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3158 setFocusedWindow(windowTop);
3159 windowTop->consumeFocusEvent(true);
3160
3161 setFocusedWindow(windowSecond, windowTop);
3162 windowSecond->consumeFocusEvent(true);
3163 windowTop->consumeFocusEvent(false);
3164
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003165 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3166 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003167
3168 // Focused window should receive event.
3169 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3170}
3171
3172TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3173 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3174 sp<FakeWindowHandle> windowTop =
3175 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3176 sp<FakeWindowHandle> windowSecond =
3177 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3178 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3179
3180 windowTop->setFocusable(true);
3181 windowSecond->setFocusable(true);
3182 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3183 setFocusedWindow(windowSecond, windowTop);
3184
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003185 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3186 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003187
3188 // Event should be dropped.
3189 windowTop->assertNoEvents();
3190 windowSecond->assertNoEvents();
3191}
3192
3193TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3194 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3195 sp<FakeWindowHandle> window =
3196 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3197 sp<FakeWindowHandle> previousFocusedWindow =
3198 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3199 ADISPLAY_ID_DEFAULT);
3200 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3201
3202 window->setFocusable(true);
3203 previousFocusedWindow->setFocusable(true);
3204 window->setVisible(false);
3205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3206 setFocusedWindow(previousFocusedWindow);
3207 previousFocusedWindow->consumeFocusEvent(true);
3208
3209 // Requesting focus on invisible window takes focus from currently focused window.
3210 setFocusedWindow(window);
3211 previousFocusedWindow->consumeFocusEvent(false);
3212
3213 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003215 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003216 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003217
3218 // Window does not get focus event or key down.
3219 window->assertNoEvents();
3220
3221 // Window becomes visible.
3222 window->setVisible(true);
3223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3224
3225 // Window receives focus event.
3226 window->consumeFocusEvent(true);
3227 // Focused window receives key down.
3228 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3229}
3230
Vishnu Nair599f1412021-06-21 10:39:58 -07003231TEST_F(InputDispatcherTest, DisplayRemoved) {
3232 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3233 sp<FakeWindowHandle> window =
3234 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3236
3237 // window is granted focus.
3238 window->setFocusable(true);
3239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3240 setFocusedWindow(window);
3241 window->consumeFocusEvent(true);
3242
3243 // When a display is removed window loses focus.
3244 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3245 window->consumeFocusEvent(false);
3246}
3247
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003248/**
3249 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3250 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3251 * of the 'slipperyEnterWindow'.
3252 *
3253 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3254 * a way so that the touched location is no longer covered by the top window.
3255 *
3256 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3257 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3258 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3259 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3260 * with ACTION_DOWN).
3261 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3262 * window moved itself away from the touched location and had Flag::SLIPPERY.
3263 *
3264 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3265 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3266 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3267 *
3268 * In this test, we ensure that the event received by the bottom window has
3269 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3270 */
3271TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3272 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3273 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3274
3275 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3276 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3277
3278 sp<FakeWindowHandle> slipperyExitWindow =
3279 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003280 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003281 // Make sure this one overlaps the bottom window
3282 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3283 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3284 // one. Windows with the same owner are not considered to be occluding each other.
3285 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3286
3287 sp<FakeWindowHandle> slipperyEnterWindow =
3288 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3289 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3290
3291 mDispatcher->setInputWindows(
3292 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3293
3294 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3295 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3296 ADISPLAY_ID_DEFAULT, {{50, 50}});
3297 mDispatcher->notifyMotion(&args);
3298 slipperyExitWindow->consumeMotionDown();
3299 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3300 mDispatcher->setInputWindows(
3301 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3302
3303 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3304 ADISPLAY_ID_DEFAULT, {{51, 51}});
3305 mDispatcher->notifyMotion(&args);
3306
3307 slipperyExitWindow->consumeMotionCancel();
3308
3309 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3310 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3311}
3312
Garfield Tan1c7bc862020-01-28 13:24:04 -08003313class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3314protected:
3315 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3316 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3317
Chris Yea209fde2020-07-22 13:54:51 -07003318 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003319 sp<FakeWindowHandle> mWindow;
3320
3321 virtual void SetUp() override {
3322 mFakePolicy = new FakeInputDispatcherPolicy();
3323 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003324 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003325 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3326 ASSERT_EQ(OK, mDispatcher->start());
3327
3328 setUpWindow();
3329 }
3330
3331 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003332 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003333 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3334
Vishnu Nair47074b82020-08-14 11:54:47 -07003335 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003337 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003338 mWindow->consumeFocusEvent(true);
3339 }
3340
Chris Ye2ad95392020-09-01 13:44:44 -07003341 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003342 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003343 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003344 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3345 mDispatcher->notifyKey(&keyArgs);
3346
3347 // Window should receive key down event.
3348 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3349 }
3350
3351 void expectKeyRepeatOnce(int32_t repeatCount) {
3352 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3353 InputEvent* repeatEvent = mWindow->consume();
3354 ASSERT_NE(nullptr, repeatEvent);
3355
3356 uint32_t eventType = repeatEvent->getType();
3357 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3358
3359 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3360 uint32_t eventAction = repeatKeyEvent->getAction();
3361 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3362 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3363 }
3364
Chris Ye2ad95392020-09-01 13:44:44 -07003365 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003366 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003367 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003368 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3369 mDispatcher->notifyKey(&keyArgs);
3370
3371 // Window should receive key down event.
3372 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3373 0 /*expectedFlags*/);
3374 }
3375};
3376
3377TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003378 sendAndConsumeKeyDown(1 /* deviceId */);
3379 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3380 expectKeyRepeatOnce(repeatCount);
3381 }
3382}
3383
3384TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3385 sendAndConsumeKeyDown(1 /* deviceId */);
3386 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3387 expectKeyRepeatOnce(repeatCount);
3388 }
3389 sendAndConsumeKeyDown(2 /* deviceId */);
3390 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003391 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3392 expectKeyRepeatOnce(repeatCount);
3393 }
3394}
3395
3396TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003397 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003398 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003399 sendAndConsumeKeyUp(1 /* deviceId */);
3400 mWindow->assertNoEvents();
3401}
3402
3403TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3404 sendAndConsumeKeyDown(1 /* deviceId */);
3405 expectKeyRepeatOnce(1 /*repeatCount*/);
3406 sendAndConsumeKeyDown(2 /* deviceId */);
3407 expectKeyRepeatOnce(1 /*repeatCount*/);
3408 // Stale key up from device 1.
3409 sendAndConsumeKeyUp(1 /* deviceId */);
3410 // Device 2 is still down, keep repeating
3411 expectKeyRepeatOnce(2 /*repeatCount*/);
3412 expectKeyRepeatOnce(3 /*repeatCount*/);
3413 // Device 2 key up
3414 sendAndConsumeKeyUp(2 /* deviceId */);
3415 mWindow->assertNoEvents();
3416}
3417
3418TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3419 sendAndConsumeKeyDown(1 /* deviceId */);
3420 expectKeyRepeatOnce(1 /*repeatCount*/);
3421 sendAndConsumeKeyDown(2 /* deviceId */);
3422 expectKeyRepeatOnce(1 /*repeatCount*/);
3423 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3424 sendAndConsumeKeyUp(2 /* deviceId */);
3425 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003426 mWindow->assertNoEvents();
3427}
3428
liushenxiang42232912021-05-21 20:24:09 +08003429TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3430 sendAndConsumeKeyDown(DEVICE_ID);
3431 expectKeyRepeatOnce(1 /*repeatCount*/);
3432 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3433 mDispatcher->notifyDeviceReset(&args);
3434 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3435 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3436 mWindow->assertNoEvents();
3437}
3438
Garfield Tan1c7bc862020-01-28 13:24:04 -08003439TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003440 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003441 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3442 InputEvent* repeatEvent = mWindow->consume();
3443 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3444 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3445 IdGenerator::getSource(repeatEvent->getId()));
3446 }
3447}
3448
3449TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003450 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003451
3452 std::unordered_set<int32_t> idSet;
3453 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3454 InputEvent* repeatEvent = mWindow->consume();
3455 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3456 int32_t id = repeatEvent->getId();
3457 EXPECT_EQ(idSet.end(), idSet.find(id));
3458 idSet.insert(id);
3459 }
3460}
3461
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003462/* Test InputDispatcher for MultiDisplay */
3463class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3464public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003465 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003466 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003467
Chris Yea209fde2020-07-22 13:54:51 -07003468 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003469 windowInPrimary =
3470 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003471
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003472 // Set focus window for primary display, but focused display would be second one.
3473 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003474 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003476 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003477 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003478
Chris Yea209fde2020-07-22 13:54:51 -07003479 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003480 windowInSecondary =
3481 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003482 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003483 // Set focus display to second one.
3484 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3485 // Set focus window for second display.
3486 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003487 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003488 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003489 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003490 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003491 }
3492
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003493 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003494 InputDispatcherTest::TearDown();
3495
Chris Yea209fde2020-07-22 13:54:51 -07003496 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003497 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003498 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003499 windowInSecondary.clear();
3500 }
3501
3502protected:
Chris Yea209fde2020-07-22 13:54:51 -07003503 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003504 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003505 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003506 sp<FakeWindowHandle> windowInSecondary;
3507};
3508
3509TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3510 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3513 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003514 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003515 windowInSecondary->assertNoEvents();
3516
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003517 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3520 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003521 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003522 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003523}
3524
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003525TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003526 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3528 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003529 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003530 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003531 windowInSecondary->assertNoEvents();
3532
3533 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003535 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003536 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003537 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003538
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003539 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003540 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003541
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003542 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003543 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3544 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003545
3546 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003547 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003548 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003549 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003550 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003551 windowInSecondary->assertNoEvents();
3552}
3553
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003554// Test per-display input monitors for motion event.
3555TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003556 FakeMonitorReceiver monitorInPrimary =
3557 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3558 FakeMonitorReceiver monitorInSecondary =
3559 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003560
3561 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003565 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003566 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003567 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003568 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003569
3570 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003574 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003575 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003576 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003577 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003578
3579 // Test inject a non-pointer motion event.
3580 // If specific a display, it will dispatch to the focused window of particular display,
3581 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003585 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003586 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003587 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003588 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003589}
3590
3591// Test per-display input monitors for key event.
3592TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003593 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003594 FakeMonitorReceiver monitorInPrimary =
3595 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3596 FakeMonitorReceiver monitorInSecondary =
3597 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003598
3599 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3601 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003602 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003603 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003604 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003605 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003606}
3607
Vishnu Nair958da932020-08-21 17:12:37 -07003608TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3609 sp<FakeWindowHandle> secondWindowInPrimary =
3610 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3611 secondWindowInPrimary->setFocusable(true);
3612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3613 setFocusedWindow(secondWindowInPrimary);
3614 windowInPrimary->consumeFocusEvent(false);
3615 secondWindowInPrimary->consumeFocusEvent(true);
3616
3617 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3619 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003620 windowInPrimary->assertNoEvents();
3621 windowInSecondary->assertNoEvents();
3622 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3623}
3624
Jackal Guof9696682018-10-05 12:23:23 +08003625class InputFilterTest : public InputDispatcherTest {
3626protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003627 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3628 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003629 NotifyMotionArgs motionArgs;
3630
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003631 motionArgs =
3632 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003633 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003634 motionArgs =
3635 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003636 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003637 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003638 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003639 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3640 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003641 } else {
3642 mFakePolicy->assertFilterInputEventWasNotCalled();
3643 }
3644 }
3645
3646 void testNotifyKey(bool expectToBeFiltered) {
3647 NotifyKeyArgs keyArgs;
3648
3649 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3650 mDispatcher->notifyKey(&keyArgs);
3651 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3652 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003653 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003654
3655 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003656 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003657 } else {
3658 mFakePolicy->assertFilterInputEventWasNotCalled();
3659 }
3660 }
3661};
3662
3663// Test InputFilter for MotionEvent
3664TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3665 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3666 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3667 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3668
3669 // Enable InputFilter
3670 mDispatcher->setInputFilterEnabled(true);
3671 // Test touch on both primary and second display, and check if both events are filtered.
3672 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3673 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3674
3675 // Disable InputFilter
3676 mDispatcher->setInputFilterEnabled(false);
3677 // Test touch on both primary and second display, and check if both events aren't filtered.
3678 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3679 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3680}
3681
3682// Test InputFilter for KeyEvent
3683TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3684 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3685 testNotifyKey(/*expectToBeFiltered*/ false);
3686
3687 // Enable InputFilter
3688 mDispatcher->setInputFilterEnabled(true);
3689 // Send a key event, and check if it is filtered.
3690 testNotifyKey(/*expectToBeFiltered*/ true);
3691
3692 // Disable InputFilter
3693 mDispatcher->setInputFilterEnabled(false);
3694 // Send a key event, and check if it isn't filtered.
3695 testNotifyKey(/*expectToBeFiltered*/ false);
3696}
3697
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003698// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3699// logical display coordinate space.
3700TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3701 ui::Transform firstDisplayTransform;
3702 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3703 ui::Transform secondDisplayTransform;
3704 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3705
3706 std::vector<gui::DisplayInfo> displayInfos(2);
3707 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3708 displayInfos[0].transform = firstDisplayTransform;
3709 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3710 displayInfos[1].transform = secondDisplayTransform;
3711
3712 mDispatcher->onWindowInfosChanged({}, displayInfos);
3713
3714 // Enable InputFilter
3715 mDispatcher->setInputFilterEnabled(true);
3716
3717 // Ensure the correct transforms are used for the displays.
3718 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3719 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3720}
3721
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003722class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3723protected:
3724 virtual void SetUp() override {
3725 InputDispatcherTest::SetUp();
3726
3727 /**
3728 * We don't need to enable input filter to test the injected event policy, but we enabled it
3729 * here to make the tests more realistic, since this policy only matters when inputfilter is
3730 * on.
3731 */
3732 mDispatcher->setInputFilterEnabled(true);
3733
3734 std::shared_ptr<InputApplicationHandle> application =
3735 std::make_shared<FakeApplicationHandle>();
3736 mWindow =
3737 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3738
3739 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3740 mWindow->setFocusable(true);
3741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3742 setFocusedWindow(mWindow);
3743 mWindow->consumeFocusEvent(true);
3744 }
3745
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003746 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3747 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003748 KeyEvent event;
3749
3750 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3751 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3752 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3753 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3754 const int32_t additionalPolicyFlags =
3755 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3757 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3758 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3759 policyFlags | additionalPolicyFlags));
3760
3761 InputEvent* received = mWindow->consume();
3762 ASSERT_NE(nullptr, received);
3763 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003764 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3765 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3766 ASSERT_EQ(flags, keyEvent.getFlags());
3767 }
3768
3769 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3770 int32_t flags) {
3771 MotionEvent event;
3772 PointerProperties pointerProperties[1];
3773 PointerCoords pointerCoords[1];
3774 pointerProperties[0].clear();
3775 pointerProperties[0].id = 0;
3776 pointerCoords[0].clear();
3777 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3778 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3779
3780 ui::Transform identityTransform;
3781 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3782 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3783 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3784 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3785 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003786 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003787 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003788 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3789
3790 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3792 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3793 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3794 policyFlags | additionalPolicyFlags));
3795
3796 InputEvent* received = mWindow->consume();
3797 ASSERT_NE(nullptr, received);
3798 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3799 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3800 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3801 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003802 }
3803
3804private:
3805 sp<FakeWindowHandle> mWindow;
3806};
3807
3808TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003809 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3810 // filter. Without it, the event will no different from a regularly injected event, and the
3811 // injected device id will be overwritten.
3812 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3813 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003814}
3815
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003816TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003817 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003818 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3819 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3820}
3821
3822TEST_F(InputFilterInjectionPolicyTest,
3823 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3824 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3825 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3826 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003827}
3828
3829TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3830 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003831 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003832}
3833
chaviwfd6d3512019-03-25 13:23:49 -07003834class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003835 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003836 InputDispatcherTest::SetUp();
3837
Chris Yea209fde2020-07-22 13:54:51 -07003838 std::shared_ptr<FakeApplicationHandle> application =
3839 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003840 mUnfocusedWindow =
3841 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003842 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3843 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3844 // window.
chaviw3277faf2021-05-19 16:45:23 -05003845 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003846
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003847 mFocusedWindow =
3848 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3849 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003850 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003851
3852 // Set focused application.
3853 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003854 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003855
3856 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003858 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003859 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003860 }
3861
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003862 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003863 InputDispatcherTest::TearDown();
3864
3865 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003866 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003867 }
3868
3869protected:
3870 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003871 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003872 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003873};
3874
3875// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3876// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3877// the onPointerDownOutsideFocus callback.
3878TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003880 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3881 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003883 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003884
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003885 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003886 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3887}
3888
3889// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3890// DOWN on the window that doesn't have focus. Ensure no window received the
3891// onPointerDownOutsideFocus callback.
3892TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003896 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003897
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003898 ASSERT_TRUE(mDispatcher->waitForIdle());
3899 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003900}
3901
3902// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3903// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3904TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3906 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003907 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003908 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003909
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003910 ASSERT_TRUE(mDispatcher->waitForIdle());
3911 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003912}
3913
3914// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3915// DOWN on the window that already has focus. Ensure no window received the
3916// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003917TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003919 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003920 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003921 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003922 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003923
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003924 ASSERT_TRUE(mDispatcher->waitForIdle());
3925 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003926}
3927
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003928// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3929// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3930TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3931 const MotionEvent event =
3932 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3933 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3934 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3935 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3936 .build();
3937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3939 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3940
3941 ASSERT_TRUE(mDispatcher->waitForIdle());
3942 mFakePolicy->assertOnPointerDownWasNotCalled();
3943 // Ensure that the unfocused window did not receive any FOCUS events.
3944 mUnfocusedWindow->assertNoEvents();
3945}
3946
chaviwaf87b3e2019-10-01 16:59:28 -07003947// These tests ensures we can send touch events to a single client when there are multiple input
3948// windows that point to the same client token.
3949class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3950 virtual void SetUp() override {
3951 InputDispatcherTest::SetUp();
3952
Chris Yea209fde2020-07-22 13:54:51 -07003953 std::shared_ptr<FakeApplicationHandle> application =
3954 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003955 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3956 ADISPLAY_ID_DEFAULT);
3957 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3958 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003959 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003960 mWindow1->setFrame(Rect(0, 0, 100, 100));
3961
3962 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3963 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003964 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003965 mWindow2->setFrame(Rect(100, 100, 200, 200));
3966
Arthur Hung72d8dc32020-03-28 00:48:39 +00003967 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003968 }
3969
3970protected:
3971 sp<FakeWindowHandle> mWindow1;
3972 sp<FakeWindowHandle> mWindow2;
3973
3974 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003975 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003976 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3977 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003978 }
3979
3980 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3981 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003982 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003983 InputEvent* event = window->consume();
3984
3985 ASSERT_NE(nullptr, event) << name.c_str()
3986 << ": consumer should have returned non-NULL event.";
3987
3988 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3989 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3990 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3991
3992 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003993 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07003994
3995 for (size_t i = 0; i < points.size(); i++) {
3996 float expectedX = points[i].x;
3997 float expectedY = points[i].y;
3998
3999 EXPECT_EQ(expectedX, motionEvent.getX(i))
4000 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4001 << ", got " << motionEvent.getX(i);
4002 EXPECT_EQ(expectedY, motionEvent.getY(i))
4003 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4004 << ", got " << motionEvent.getY(i);
4005 }
4006 }
chaviw9eaa22c2020-07-01 16:21:27 -07004007
4008 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4009 std::vector<PointF> expectedPoints) {
4010 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4011 ADISPLAY_ID_DEFAULT, touchedPoints);
4012 mDispatcher->notifyMotion(&motionArgs);
4013
4014 // Always consume from window1 since it's the window that has the InputReceiver
4015 consumeMotionEvent(mWindow1, action, expectedPoints);
4016 }
chaviwaf87b3e2019-10-01 16:59:28 -07004017};
4018
4019TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4020 // Touch Window 1
4021 PointF touchedPoint = {10, 10};
4022 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004023 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004024
4025 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004026 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004027
4028 // Touch Window 2
4029 touchedPoint = {150, 150};
4030 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004031 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004032}
4033
chaviw9eaa22c2020-07-01 16:21:27 -07004034TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4035 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004036 mWindow2->setWindowScale(0.5f, 0.5f);
4037
4038 // Touch Window 1
4039 PointF touchedPoint = {10, 10};
4040 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004041 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004042 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004043 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004044
4045 // Touch Window 2
4046 touchedPoint = {150, 150};
4047 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004048 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4049 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004050
chaviw9eaa22c2020-07-01 16:21:27 -07004051 // Update the transform so rotation is set
4052 mWindow2->setWindowTransform(0, -1, 1, 0);
4053 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4054 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004055}
4056
chaviw9eaa22c2020-07-01 16:21:27 -07004057TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004058 mWindow2->setWindowScale(0.5f, 0.5f);
4059
4060 // Touch Window 1
4061 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4062 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004063 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004064
4065 // Touch Window 2
4066 int32_t actionPointerDown =
4067 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004068 touchedPoints.push_back(PointF{150, 150});
4069 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4070 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004071
chaviw9eaa22c2020-07-01 16:21:27 -07004072 // Release Window 2
4073 int32_t actionPointerUp =
4074 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4075 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4076 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004077
chaviw9eaa22c2020-07-01 16:21:27 -07004078 // Update the transform so rotation is set for Window 2
4079 mWindow2->setWindowTransform(0, -1, 1, 0);
4080 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4081 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004082}
4083
chaviw9eaa22c2020-07-01 16:21:27 -07004084TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004085 mWindow2->setWindowScale(0.5f, 0.5f);
4086
4087 // Touch Window 1
4088 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4089 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004090 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004091
4092 // Touch Window 2
4093 int32_t actionPointerDown =
4094 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004095 touchedPoints.push_back(PointF{150, 150});
4096 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004097
chaviw9eaa22c2020-07-01 16:21:27 -07004098 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004099
4100 // Move both windows
4101 touchedPoints = {{20, 20}, {175, 175}};
4102 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4103 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4104
chaviw9eaa22c2020-07-01 16:21:27 -07004105 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004106
chaviw9eaa22c2020-07-01 16:21:27 -07004107 // Release Window 2
4108 int32_t actionPointerUp =
4109 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4110 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4111 expectedPoints.pop_back();
4112
4113 // Touch Window 2
4114 mWindow2->setWindowTransform(0, -1, 1, 0);
4115 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4116 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4117
4118 // Move both windows
4119 touchedPoints = {{20, 20}, {175, 175}};
4120 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4121 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4122
4123 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004124}
4125
4126TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4127 mWindow1->setWindowScale(0.5f, 0.5f);
4128
4129 // Touch Window 1
4130 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4131 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004132 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004133
4134 // Touch Window 2
4135 int32_t actionPointerDown =
4136 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004137 touchedPoints.push_back(PointF{150, 150});
4138 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004139
chaviw9eaa22c2020-07-01 16:21:27 -07004140 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004141
4142 // Move both windows
4143 touchedPoints = {{20, 20}, {175, 175}};
4144 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4145 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4146
chaviw9eaa22c2020-07-01 16:21:27 -07004147 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004148}
4149
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004150class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4151 virtual void SetUp() override {
4152 InputDispatcherTest::SetUp();
4153
Chris Yea209fde2020-07-22 13:54:51 -07004154 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004155 mApplication->setDispatchingTimeout(20ms);
4156 mWindow =
4157 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4158 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004159 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004160 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004161 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4162 // window.
chaviw3277faf2021-05-19 16:45:23 -05004163 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004164
4165 // Set focused application.
4166 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4167
4168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004169 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004170 mWindow->consumeFocusEvent(true);
4171 }
4172
4173 virtual void TearDown() override {
4174 InputDispatcherTest::TearDown();
4175 mWindow.clear();
4176 }
4177
4178protected:
Chris Yea209fde2020-07-22 13:54:51 -07004179 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004180 sp<FakeWindowHandle> mWindow;
4181 static constexpr PointF WINDOW_LOCATION = {20, 20};
4182
4183 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004185 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4186 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004188 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4189 WINDOW_LOCATION));
4190 }
4191};
4192
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004193// Send a tap and respond, which should not cause an ANR.
4194TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4195 tapOnWindow();
4196 mWindow->consumeMotionDown();
4197 mWindow->consumeMotionUp();
4198 ASSERT_TRUE(mDispatcher->waitForIdle());
4199 mFakePolicy->assertNotifyAnrWasNotCalled();
4200}
4201
4202// Send a regular key and respond, which should not cause an ANR.
4203TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004204 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004205 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4206 ASSERT_TRUE(mDispatcher->waitForIdle());
4207 mFakePolicy->assertNotifyAnrWasNotCalled();
4208}
4209
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004210TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4211 mWindow->setFocusable(false);
4212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4213 mWindow->consumeFocusEvent(false);
4214
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004215 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004216 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004217 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4218 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004220 // Key will not go to window because we have no focused window.
4221 // The 'no focused window' ANR timer should start instead.
4222
4223 // Now, the focused application goes away.
4224 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4225 // The key should get dropped and there should be no ANR.
4226
4227 ASSERT_TRUE(mDispatcher->waitForIdle());
4228 mFakePolicy->assertNotifyAnrWasNotCalled();
4229}
4230
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004231// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004232// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4233// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004234TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004236 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4237 WINDOW_LOCATION));
4238
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004239 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4240 ASSERT_TRUE(sequenceNum);
4241 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004242 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004243
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004244 mWindow->finishEvent(*sequenceNum);
4245 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4246 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004247 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004248 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004249}
4250
4251// Send a key to the app and have the app not respond right away.
4252TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4253 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004255 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4256 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004257 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004258 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 ASSERT_TRUE(mDispatcher->waitForIdle());
4260}
4261
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004262// We have a focused application, but no focused window
4263TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004264 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4266 mWindow->consumeFocusEvent(false);
4267
4268 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4271 WINDOW_LOCATION));
4272 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4273 mDispatcher->waitForIdle();
4274 mFakePolicy->assertNotifyAnrWasNotCalled();
4275
4276 // Once a focused event arrives, we get an ANR for this application
4277 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4278 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004279 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004280 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004281 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004282 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004283 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004284 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004285 ASSERT_TRUE(mDispatcher->waitForIdle());
4286}
4287
4288// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004289// Make sure that we don't notify policy twice about the same ANR.
4290TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004291 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4293 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004294
4295 // Once a focused event arrives, we get an ANR for this application
4296 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4297 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004299 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004300 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004302 const std::chrono::duration appTimeout =
4303 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004304 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004305
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004306 std::this_thread::sleep_for(appTimeout);
4307 // ANR should not be raised again. It is up to policy to do that if it desires.
4308 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004309
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004310 // If we now get a focused window, the ANR should stop, but the policy handles that via
4311 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004312 ASSERT_TRUE(mDispatcher->waitForIdle());
4313}
4314
4315// We have a focused application, but no focused window
4316TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004317 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4319 mWindow->consumeFocusEvent(false);
4320
4321 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004323 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004324 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4325 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004326
4327 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004328 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004329
4330 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004331 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004332 ASSERT_TRUE(mDispatcher->waitForIdle());
4333 mWindow->assertNoEvents();
4334}
4335
4336/**
4337 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4338 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4339 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4340 * the ANR mechanism should still work.
4341 *
4342 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4343 * DOWN event, while not responding on the second one.
4344 */
4345TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4346 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4347 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4348 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4349 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4350 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004351 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004352
4353 // Now send ACTION_UP, with identical timestamp
4354 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4355 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4356 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4357 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004359
4360 // We have now sent down and up. Let's consume first event and then ANR on the second.
4361 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4362 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004363 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004364}
4365
4366// If an app is not responding to a key event, gesture monitors should continue to receive
4367// new motion events
4368TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4369 FakeMonitorReceiver monitor =
4370 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4371 true /*isGestureMonitor*/);
4372
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4374 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004375 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004377
4378 // Stuck on the ACTION_UP
4379 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004380 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004381
4382 // New tap will go to the gesture monitor, but not to the window
4383 tapOnWindow();
4384 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4385 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4386
4387 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4388 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004389 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004390 mWindow->assertNoEvents();
4391 monitor.assertNoEvents();
4392}
4393
4394// If an app is not responding to a motion event, gesture monitors should continue to receive
4395// new motion events
4396TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4397 FakeMonitorReceiver monitor =
4398 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4399 true /*isGestureMonitor*/);
4400
4401 tapOnWindow();
4402 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4403 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4404
4405 mWindow->consumeMotionDown();
4406 // Stuck on the ACTION_UP
4407 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004408 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004409
4410 // New tap will go to the gesture monitor, but not to the window
4411 tapOnWindow();
4412 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4413 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4414
4415 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4416 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004417 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004418 mWindow->assertNoEvents();
4419 monitor.assertNoEvents();
4420}
4421
4422// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4423// process events, you don't get an anr. When the window later becomes unresponsive again, you
4424// get an ANR again.
4425// 1. tap -> block on ACTION_UP -> receive ANR
4426// 2. consume all pending events (= queue becomes healthy again)
4427// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4428TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4429 tapOnWindow();
4430
4431 mWindow->consumeMotionDown();
4432 // Block on ACTION_UP
4433 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004434 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004435 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4436 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004437 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004438 mWindow->assertNoEvents();
4439
4440 tapOnWindow();
4441 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004442 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004443 mWindow->consumeMotionUp();
4444
4445 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004446 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004447 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448 mWindow->assertNoEvents();
4449}
4450
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004451// If a connection remains unresponsive for a while, make sure policy is only notified once about
4452// it.
4453TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4456 WINDOW_LOCATION));
4457
4458 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004459 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004461 // 'notifyConnectionUnresponsive' should only be called once per connection
4462 mFakePolicy->assertNotifyAnrWasNotCalled();
4463 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004464 mWindow->consumeMotionDown();
4465 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4466 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4467 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004468 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004469 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004470 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471}
4472
4473/**
4474 * If a window is processing a motion event, and then a key event comes in, the key event should
4475 * not to to the focused window until the motion is processed.
4476 *
4477 * Warning!!!
4478 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4479 * and the injection timeout that we specify when injecting the key.
4480 * We must have the injection timeout (10ms) be smaller than
4481 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4482 *
4483 * If that value changes, this test should also change.
4484 */
4485TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4486 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4487 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4488
4489 tapOnWindow();
4490 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4491 ASSERT_TRUE(downSequenceNum);
4492 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4493 ASSERT_TRUE(upSequenceNum);
4494 // Don't finish the events yet, and send a key
4495 // Injection will "succeed" because we will eventually give up and send the key to the focused
4496 // window even if motions are still being processed. But because the injection timeout is short,
4497 // we will receive INJECTION_TIMED_OUT as the result.
4498
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4502 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004503 // Key will not be sent to the window, yet, because the window is still processing events
4504 // and the key remains pending, waiting for the touch events to be processed
4505 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4506 ASSERT_FALSE(keySequenceNum);
4507
4508 std::this_thread::sleep_for(500ms);
4509 // if we wait long enough though, dispatcher will give up, and still send the key
4510 // to the focused window, even though we have not yet finished the motion event
4511 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4512 mWindow->finishEvent(*downSequenceNum);
4513 mWindow->finishEvent(*upSequenceNum);
4514}
4515
4516/**
4517 * If a window is processing a motion event, and then a key event comes in, the key event should
4518 * not go to the focused window until the motion is processed.
4519 * If then a new motion comes in, then the pending key event should be going to the currently
4520 * focused window right away.
4521 */
4522TEST_F(InputDispatcherSingleWindowAnr,
4523 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4524 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4526
4527 tapOnWindow();
4528 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4529 ASSERT_TRUE(downSequenceNum);
4530 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4531 ASSERT_TRUE(upSequenceNum);
4532 // Don't finish the events yet, and send a key
4533 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 // At this point, key is still pending, and should not be sent to the application yet.
4538 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4539 ASSERT_FALSE(keySequenceNum);
4540
4541 // Now tap down again. It should cause the pending key to go to the focused window right away.
4542 tapOnWindow();
4543 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4544 // the other events yet. We can finish events in any order.
4545 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4546 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4547 mWindow->consumeMotionDown();
4548 mWindow->consumeMotionUp();
4549 mWindow->assertNoEvents();
4550}
4551
4552class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4553 virtual void SetUp() override {
4554 InputDispatcherTest::SetUp();
4555
Chris Yea209fde2020-07-22 13:54:51 -07004556 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004557 mApplication->setDispatchingTimeout(10ms);
4558 mUnfocusedWindow =
4559 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4560 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4561 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4562 // window.
4563 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004564 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4565 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4566 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567
4568 mFocusedWindow =
4569 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004570 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004572 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004573
4574 // Set focused application.
4575 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004576 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577
4578 // Expect one focus window exist in display.
4579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004580 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 mFocusedWindow->consumeFocusEvent(true);
4582 }
4583
4584 virtual void TearDown() override {
4585 InputDispatcherTest::TearDown();
4586
4587 mUnfocusedWindow.clear();
4588 mFocusedWindow.clear();
4589 }
4590
4591protected:
Chris Yea209fde2020-07-22 13:54:51 -07004592 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593 sp<FakeWindowHandle> mUnfocusedWindow;
4594 sp<FakeWindowHandle> mFocusedWindow;
4595 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4596 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4597 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4598
4599 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4600
4601 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4602
4603private:
4604 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4607 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4610 location));
4611 }
4612};
4613
4614// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4615// should be ANR'd first.
4616TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4619 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621 mFocusedWindow->consumeMotionDown();
4622 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4623 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4624 // We consumed all events, so no ANR
4625 ASSERT_TRUE(mDispatcher->waitForIdle());
4626 mFakePolicy->assertNotifyAnrWasNotCalled();
4627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4630 FOCUSED_WINDOW_LOCATION));
4631 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4632 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004633
4634 const std::chrono::duration timeout =
4635 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004636 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004637 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4638 // sequence to make it consistent
4639 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004640 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004641 mFocusedWindow->consumeMotionDown();
4642 // This cancel is generated because the connection was unresponsive
4643 mFocusedWindow->consumeMotionCancel();
4644 mFocusedWindow->assertNoEvents();
4645 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004646 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004647 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004648 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649}
4650
4651// If we have 2 windows with identical timeouts that are both unresponsive,
4652// it doesn't matter which order they should have ANR.
4653// But we should receive ANR for both.
4654TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4655 // Set the timeout for unfocused window to match the focused window
4656 mUnfocusedWindow->setDispatchingTimeout(10ms);
4657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4658
4659 tapOnFocusedWindow();
4660 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004661 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4662 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663
4664 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004665 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4666 mFocusedWindow->getToken() == anrConnectionToken2);
4667 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4668 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004669
4670 ASSERT_TRUE(mDispatcher->waitForIdle());
4671 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004672
4673 mFocusedWindow->consumeMotionDown();
4674 mFocusedWindow->consumeMotionUp();
4675 mUnfocusedWindow->consumeMotionOutside();
4676
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004677 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4678 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004679
4680 // Both applications should be marked as responsive, in any order
4681 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4682 mFocusedWindow->getToken() == responsiveToken2);
4683 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4684 mUnfocusedWindow->getToken() == responsiveToken2);
4685 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004686}
4687
4688// If a window is already not responding, the second tap on the same window should be ignored.
4689// We should also log an error to account for the dropped event (not tested here).
4690// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4691TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4692 tapOnFocusedWindow();
4693 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4694 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4695 // Receive the events, but don't respond
4696 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4697 ASSERT_TRUE(downEventSequenceNum);
4698 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4699 ASSERT_TRUE(upEventSequenceNum);
4700 const std::chrono::duration timeout =
4701 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004702 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703
4704 // Tap once again
4705 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004706 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004707 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4708 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4711 FOCUSED_WINDOW_LOCATION));
4712 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4713 // valid touch target
4714 mUnfocusedWindow->assertNoEvents();
4715
4716 // Consume the first tap
4717 mFocusedWindow->finishEvent(*downEventSequenceNum);
4718 mFocusedWindow->finishEvent(*upEventSequenceNum);
4719 ASSERT_TRUE(mDispatcher->waitForIdle());
4720 // The second tap did not go to the focused window
4721 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004722 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004723 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724 mFakePolicy->assertNotifyAnrWasNotCalled();
4725}
4726
4727// If you tap outside of all windows, there will not be ANR
4728TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004729 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4731 LOCATION_OUTSIDE_ALL_WINDOWS));
4732 ASSERT_TRUE(mDispatcher->waitForIdle());
4733 mFakePolicy->assertNotifyAnrWasNotCalled();
4734}
4735
4736// Since the focused window is paused, tapping on it should not produce any events
4737TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4738 mFocusedWindow->setPaused(true);
4739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4740
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4743 FOCUSED_WINDOW_LOCATION));
4744
4745 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4746 ASSERT_TRUE(mDispatcher->waitForIdle());
4747 // Should not ANR because the window is paused, and touches shouldn't go to it
4748 mFakePolicy->assertNotifyAnrWasNotCalled();
4749
4750 mFocusedWindow->assertNoEvents();
4751 mUnfocusedWindow->assertNoEvents();
4752}
4753
4754/**
4755 * If a window is processing a motion event, and then a key event comes in, the key event should
4756 * not to to the focused window until the motion is processed.
4757 * If a different window becomes focused at this time, the key should go to that window instead.
4758 *
4759 * Warning!!!
4760 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4761 * and the injection timeout that we specify when injecting the key.
4762 * We must have the injection timeout (10ms) be smaller than
4763 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4764 *
4765 * If that value changes, this test should also change.
4766 */
4767TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4768 // Set a long ANR timeout to prevent it from triggering
4769 mFocusedWindow->setDispatchingTimeout(2s);
4770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4771
4772 tapOnUnfocusedWindow();
4773 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4774 ASSERT_TRUE(downSequenceNum);
4775 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4776 ASSERT_TRUE(upSequenceNum);
4777 // Don't finish the events yet, and send a key
4778 // Injection will succeed because we will eventually give up and send the key to the focused
4779 // window even if motions are still being processed.
4780
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004781 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004782 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004783 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785 // Key will not be sent to the window, yet, because the window is still processing events
4786 // and the key remains pending, waiting for the touch events to be processed
4787 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4788 ASSERT_FALSE(keySequenceNum);
4789
4790 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004791 mFocusedWindow->setFocusable(false);
4792 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004794 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795
4796 // Focus events should precede the key events
4797 mUnfocusedWindow->consumeFocusEvent(true);
4798 mFocusedWindow->consumeFocusEvent(false);
4799
4800 // Finish the tap events, which should unblock dispatcher
4801 mUnfocusedWindow->finishEvent(*downSequenceNum);
4802 mUnfocusedWindow->finishEvent(*upSequenceNum);
4803
4804 // Now that all queues are cleared and no backlog in the connections, the key event
4805 // can finally go to the newly focused "mUnfocusedWindow".
4806 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4807 mFocusedWindow->assertNoEvents();
4808 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004809 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810}
4811
4812// When the touch stream is split across 2 windows, and one of them does not respond,
4813// then ANR should be raised and the touch should be canceled for the unresponsive window.
4814// The other window should not be affected by that.
4815TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4816 // Touch Window 1
4817 NotifyMotionArgs motionArgs =
4818 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4819 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4820 mDispatcher->notifyMotion(&motionArgs);
4821 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4822 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4823
4824 // Touch Window 2
4825 int32_t actionPointerDown =
4826 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4827
4828 motionArgs =
4829 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4830 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4831 mDispatcher->notifyMotion(&motionArgs);
4832
4833 const std::chrono::duration timeout =
4834 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004835 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836
4837 mUnfocusedWindow->consumeMotionDown();
4838 mFocusedWindow->consumeMotionDown();
4839 // Focused window may or may not receive ACTION_MOVE
4840 // But it should definitely receive ACTION_CANCEL due to the ANR
4841 InputEvent* event;
4842 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4843 ASSERT_TRUE(moveOrCancelSequenceNum);
4844 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4845 ASSERT_NE(nullptr, event);
4846 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4847 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4848 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4849 mFocusedWindow->consumeMotionCancel();
4850 } else {
4851 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4852 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004854 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 mUnfocusedWindow->assertNoEvents();
4857 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004858 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859}
4860
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004861/**
4862 * If we have no focused window, and a key comes in, we start the ANR timer.
4863 * The focused application should add a focused window before the timer runs out to prevent ANR.
4864 *
4865 * If the user touches another application during this time, the key should be dropped.
4866 * Next, if a new focused window comes in, without toggling the focused application,
4867 * then no ANR should occur.
4868 *
4869 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4870 * but in some cases the policy may not update the focused application.
4871 */
4872TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4873 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4874 std::make_shared<FakeApplicationHandle>();
4875 focusedApplication->setDispatchingTimeout(60ms);
4876 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4877 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4878 mFocusedWindow->setFocusable(false);
4879
4880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4881 mFocusedWindow->consumeFocusEvent(false);
4882
4883 // Send a key. The ANR timer should start because there is no focused window.
4884 // 'focusedApplication' will get blamed if this timer completes.
4885 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004886 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004887 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004888 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4889 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004891
4892 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4893 // then the injected touches won't cause the focused event to get dropped.
4894 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4895 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4896 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4897 // For this test, it means that the key would get delivered to the window once it becomes
4898 // focused.
4899 std::this_thread::sleep_for(10ms);
4900
4901 // Touch unfocused window. This should force the pending key to get dropped.
4902 NotifyMotionArgs motionArgs =
4903 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4904 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4905 mDispatcher->notifyMotion(&motionArgs);
4906
4907 // We do not consume the motion right away, because that would require dispatcher to first
4908 // process (== drop) the key event, and by that time, ANR will be raised.
4909 // Set the focused window first.
4910 mFocusedWindow->setFocusable(true);
4911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4912 setFocusedWindow(mFocusedWindow);
4913 mFocusedWindow->consumeFocusEvent(true);
4914 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4915 // to another application. This could be a bug / behaviour in the policy.
4916
4917 mUnfocusedWindow->consumeMotionDown();
4918
4919 ASSERT_TRUE(mDispatcher->waitForIdle());
4920 // Should not ANR because we actually have a focused window. It was just added too slowly.
4921 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4922}
4923
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004924// These tests ensure we cannot send touch events to a window that's positioned behind a window
4925// that has feature NO_INPUT_CHANNEL.
4926// Layout:
4927// Top (closest to user)
4928// mNoInputWindow (above all windows)
4929// mBottomWindow
4930// Bottom (furthest from user)
4931class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4932 virtual void SetUp() override {
4933 InputDispatcherTest::SetUp();
4934
4935 mApplication = std::make_shared<FakeApplicationHandle>();
4936 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4937 "Window without input channel", ADISPLAY_ID_DEFAULT,
4938 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4939
chaviw3277faf2021-05-19 16:45:23 -05004940 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004941 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4942 // It's perfectly valid for this window to not have an associated input channel
4943
4944 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4945 ADISPLAY_ID_DEFAULT);
4946 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4947
4948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4949 }
4950
4951protected:
4952 std::shared_ptr<FakeApplicationHandle> mApplication;
4953 sp<FakeWindowHandle> mNoInputWindow;
4954 sp<FakeWindowHandle> mBottomWindow;
4955};
4956
4957TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4958 PointF touchedPoint = {10, 10};
4959
4960 NotifyMotionArgs motionArgs =
4961 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4962 ADISPLAY_ID_DEFAULT, {touchedPoint});
4963 mDispatcher->notifyMotion(&motionArgs);
4964
4965 mNoInputWindow->assertNoEvents();
4966 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4967 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4968 // and therefore should prevent mBottomWindow from receiving touches
4969 mBottomWindow->assertNoEvents();
4970}
4971
4972/**
4973 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4974 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4975 */
4976TEST_F(InputDispatcherMultiWindowOcclusionTests,
4977 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4978 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4979 "Window with input channel and NO_INPUT_CHANNEL",
4980 ADISPLAY_ID_DEFAULT);
4981
chaviw3277faf2021-05-19 16:45:23 -05004982 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004983 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4984 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4985
4986 PointF touchedPoint = {10, 10};
4987
4988 NotifyMotionArgs motionArgs =
4989 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4990 ADISPLAY_ID_DEFAULT, {touchedPoint});
4991 mDispatcher->notifyMotion(&motionArgs);
4992
4993 mNoInputWindow->assertNoEvents();
4994 mBottomWindow->assertNoEvents();
4995}
4996
Vishnu Nair958da932020-08-21 17:12:37 -07004997class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4998protected:
4999 std::shared_ptr<FakeApplicationHandle> mApp;
5000 sp<FakeWindowHandle> mWindow;
5001 sp<FakeWindowHandle> mMirror;
5002
5003 virtual void SetUp() override {
5004 InputDispatcherTest::SetUp();
5005 mApp = std::make_shared<FakeApplicationHandle>();
5006 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5007 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5008 mWindow->getToken());
5009 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5010 mWindow->setFocusable(true);
5011 mMirror->setFocusable(true);
5012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5013 }
5014};
5015
5016TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5017 // Request focus on a mirrored window
5018 setFocusedWindow(mMirror);
5019
5020 // window gets focused
5021 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5023 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005024 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5025}
5026
5027// A focused & mirrored window remains focused only if the window and its mirror are both
5028// focusable.
5029TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5030 setFocusedWindow(mMirror);
5031
5032 // window gets focused
5033 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5035 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005036 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005037 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5038 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005039 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5040
5041 mMirror->setFocusable(false);
5042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5043
5044 // window loses focus since one of the windows associated with the token in not focusable
5045 mWindow->consumeFocusEvent(false);
5046
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005047 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5048 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005049 mWindow->assertNoEvents();
5050}
5051
5052// A focused & mirrored window remains focused until the window and its mirror both become
5053// invisible.
5054TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5055 setFocusedWindow(mMirror);
5056
5057 // window gets focused
5058 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5060 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005061 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5063 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005064 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5065
5066 mMirror->setVisible(false);
5067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5068
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5070 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005071 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5073 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005074 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5075
5076 mWindow->setVisible(false);
5077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5078
5079 // window loses focus only after all windows associated with the token become invisible.
5080 mWindow->consumeFocusEvent(false);
5081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5083 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005084 mWindow->assertNoEvents();
5085}
5086
5087// A focused & mirrored window remains focused until both windows are removed.
5088TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5089 setFocusedWindow(mMirror);
5090
5091 // window gets focused
5092 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5094 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005095 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5097 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005098 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5099
5100 // single window is removed but the window token remains focused
5101 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5102
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5104 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005105 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5107 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005108 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5109
5110 // Both windows are removed
5111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5112 mWindow->consumeFocusEvent(false);
5113
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005114 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5115 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005116 mWindow->assertNoEvents();
5117}
5118
5119// Focus request can be pending until one window becomes visible.
5120TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5121 // Request focus on an invisible mirror.
5122 mWindow->setVisible(false);
5123 mMirror->setVisible(false);
5124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5125 setFocusedWindow(mMirror);
5126
5127 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005129 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005130 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005131
5132 mMirror->setVisible(true);
5133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5134
5135 // window gets focused
5136 mWindow->consumeFocusEvent(true);
5137 // window gets the pending key event
5138 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5139}
Prabir Pradhan99987712020-11-10 18:43:05 -08005140
5141class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5142protected:
5143 std::shared_ptr<FakeApplicationHandle> mApp;
5144 sp<FakeWindowHandle> mWindow;
5145 sp<FakeWindowHandle> mSecondWindow;
5146
5147 void SetUp() override {
5148 InputDispatcherTest::SetUp();
5149 mApp = std::make_shared<FakeApplicationHandle>();
5150 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5151 mWindow->setFocusable(true);
5152 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5153 mSecondWindow->setFocusable(true);
5154
5155 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5157
5158 setFocusedWindow(mWindow);
5159 mWindow->consumeFocusEvent(true);
5160 }
5161
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005162 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5163 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005164 mDispatcher->notifyPointerCaptureChanged(&args);
5165 }
5166
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005167 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5168 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005169 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005170 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5171 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005172 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005173 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005174 }
5175};
5176
5177TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5178 // Ensure that capture cannot be obtained for unfocused windows.
5179 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5180 mFakePolicy->assertSetPointerCaptureNotCalled();
5181 mSecondWindow->assertNoEvents();
5182
5183 // Ensure that capture can be enabled from the focus window.
5184 requestAndVerifyPointerCapture(mWindow, true);
5185
5186 // Ensure that capture cannot be disabled from a window that does not have capture.
5187 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5188 mFakePolicy->assertSetPointerCaptureNotCalled();
5189
5190 // Ensure that capture can be disabled from the window with capture.
5191 requestAndVerifyPointerCapture(mWindow, false);
5192}
5193
5194TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005195 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005196
5197 setFocusedWindow(mSecondWindow);
5198
5199 // Ensure that the capture disabled event was sent first.
5200 mWindow->consumeCaptureEvent(false);
5201 mWindow->consumeFocusEvent(false);
5202 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005203 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005204
5205 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005206 notifyPointerCaptureChanged({});
5207 notifyPointerCaptureChanged(request);
5208 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005209 mWindow->assertNoEvents();
5210 mSecondWindow->assertNoEvents();
5211 mFakePolicy->assertSetPointerCaptureNotCalled();
5212}
5213
5214TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005215 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005216
5217 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005218 notifyPointerCaptureChanged({});
5219 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005220
5221 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005222 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005223 mWindow->consumeCaptureEvent(false);
5224 mWindow->assertNoEvents();
5225}
5226
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005227TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5228 requestAndVerifyPointerCapture(mWindow, true);
5229
5230 // The first window loses focus.
5231 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005232 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005233 mWindow->consumeCaptureEvent(false);
5234
5235 // Request Pointer Capture from the second window before the notification from InputReader
5236 // arrives.
5237 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005238 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005239
5240 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005241 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005242
5243 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005244 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005245
5246 mSecondWindow->consumeFocusEvent(true);
5247 mSecondWindow->consumeCaptureEvent(true);
5248}
5249
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005250TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5251 // App repeatedly enables and disables capture.
5252 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5253 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5254 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5255 mFakePolicy->assertSetPointerCaptureCalled(false);
5256 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5257 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5258
5259 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5260 // first request is now stale, this should do nothing.
5261 notifyPointerCaptureChanged(firstRequest);
5262 mWindow->assertNoEvents();
5263
5264 // InputReader notifies that the second request was enabled.
5265 notifyPointerCaptureChanged(secondRequest);
5266 mWindow->consumeCaptureEvent(true);
5267}
5268
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005269class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5270protected:
5271 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005272
5273 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5274 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5275
5276 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5277 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5278
5279 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5280 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5281 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5282 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5283 MAXIMUM_OBSCURING_OPACITY);
5284
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005285 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005286 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005287 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005288
5289 sp<FakeWindowHandle> mTouchWindow;
5290
5291 virtual void SetUp() override {
5292 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005293 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005294 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5295 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5296 }
5297
5298 virtual void TearDown() override {
5299 InputDispatcherTest::TearDown();
5300 mTouchWindow.clear();
5301 }
5302
chaviw3277faf2021-05-19 16:45:23 -05005303 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5304 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005305 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005306 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005307 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005308 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005309 return window;
5310 }
5311
5312 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5313 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5314 sp<FakeWindowHandle> window =
5315 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5316 // Generate an arbitrary PID based on the UID
5317 window->setOwnerInfo(1777 + (uid % 10000), uid);
5318 return window;
5319 }
5320
5321 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5322 NotifyMotionArgs args =
5323 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5324 ADISPLAY_ID_DEFAULT, points);
5325 mDispatcher->notifyMotion(&args);
5326 }
5327};
5328
5329TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005330 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005331 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005333
5334 touch();
5335
5336 mTouchWindow->assertNoEvents();
5337}
5338
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005339TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005340 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5341 const sp<FakeWindowHandle>& w =
5342 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5344
5345 touch();
5346
5347 mTouchWindow->assertNoEvents();
5348}
5349
5350TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005351 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5352 const sp<FakeWindowHandle>& w =
5353 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5355
5356 touch();
5357
5358 w->assertNoEvents();
5359}
5360
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005361TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005362 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005364
5365 touch();
5366
5367 mTouchWindow->consumeAnyMotionDown();
5368}
5369
5370TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005371 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005372 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005373 w->setFrame(Rect(0, 0, 50, 50));
5374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005375
5376 touch({PointF{100, 100}});
5377
5378 mTouchWindow->consumeAnyMotionDown();
5379}
5380
5381TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005382 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005383 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005384 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5385
5386 touch();
5387
5388 mTouchWindow->consumeAnyMotionDown();
5389}
5390
5391TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5392 const sp<FakeWindowHandle>& w =
5393 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005395
5396 touch();
5397
5398 mTouchWindow->consumeAnyMotionDown();
5399}
5400
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005401TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5402 const sp<FakeWindowHandle>& w =
5403 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5405
5406 touch();
5407
5408 w->assertNoEvents();
5409}
5410
5411/**
5412 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5413 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5414 * window, the occluding window will still receive ACTION_OUTSIDE event.
5415 */
5416TEST_F(InputDispatcherUntrustedTouchesTest,
5417 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5418 const sp<FakeWindowHandle>& w =
5419 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005420 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5422
5423 touch();
5424
5425 w->consumeMotionOutside();
5426}
5427
5428TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5429 const sp<FakeWindowHandle>& w =
5430 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005431 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5433
5434 touch();
5435
5436 InputEvent* event = w->consume();
5437 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5438 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5439 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5440 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5441}
5442
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005443TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005444 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005445 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5446 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5448
5449 touch();
5450
5451 mTouchWindow->consumeAnyMotionDown();
5452}
5453
5454TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5455 const sp<FakeWindowHandle>& w =
5456 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5457 MAXIMUM_OBSCURING_OPACITY);
5458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005459
5460 touch();
5461
5462 mTouchWindow->consumeAnyMotionDown();
5463}
5464
5465TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005466 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005467 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5468 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5470
5471 touch();
5472
5473 mTouchWindow->assertNoEvents();
5474}
5475
5476TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5477 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5478 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005479 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5480 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005481 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005482 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5483 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5485
5486 touch();
5487
5488 mTouchWindow->assertNoEvents();
5489}
5490
5491TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5492 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5493 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005494 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5495 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005496 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005497 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5498 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5500
5501 touch();
5502
5503 mTouchWindow->consumeAnyMotionDown();
5504}
5505
5506TEST_F(InputDispatcherUntrustedTouchesTest,
5507 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5508 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005509 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5510 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005511 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005512 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5513 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5515
5516 touch();
5517
5518 mTouchWindow->consumeAnyMotionDown();
5519}
5520
5521TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5522 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5524 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005525 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005526 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5527 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005529
5530 touch();
5531
5532 mTouchWindow->assertNoEvents();
5533}
5534
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005535TEST_F(InputDispatcherUntrustedTouchesTest,
5536 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5537 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005538 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5539 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005540 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005541 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5542 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5544
5545 touch();
5546
5547 mTouchWindow->assertNoEvents();
5548}
5549
5550TEST_F(InputDispatcherUntrustedTouchesTest,
5551 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5552 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005553 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5554 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005555 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005556 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5557 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5559
5560 touch();
5561
5562 mTouchWindow->consumeAnyMotionDown();
5563}
5564
5565TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5566 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005567 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5568 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5570
5571 touch();
5572
5573 mTouchWindow->consumeAnyMotionDown();
5574}
5575
5576TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5577 const sp<FakeWindowHandle>& w =
5578 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5580
5581 touch();
5582
5583 mTouchWindow->consumeAnyMotionDown();
5584}
5585
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005586TEST_F(InputDispatcherUntrustedTouchesTest,
5587 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5588 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5589 const sp<FakeWindowHandle>& w =
5590 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5592
5593 touch();
5594
5595 mTouchWindow->assertNoEvents();
5596}
5597
5598TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5599 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5600 const sp<FakeWindowHandle>& w =
5601 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5603
5604 touch();
5605
5606 mTouchWindow->consumeAnyMotionDown();
5607}
5608
5609TEST_F(InputDispatcherUntrustedTouchesTest,
5610 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5611 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5612 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005613 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5614 OPACITY_ABOVE_THRESHOLD);
5615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5616
5617 touch();
5618
5619 mTouchWindow->consumeAnyMotionDown();
5620}
5621
5622TEST_F(InputDispatcherUntrustedTouchesTest,
5623 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5624 const sp<FakeWindowHandle>& w1 =
5625 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5626 OPACITY_BELOW_THRESHOLD);
5627 const sp<FakeWindowHandle>& w2 =
5628 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5629 OPACITY_BELOW_THRESHOLD);
5630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5631
5632 touch();
5633
5634 mTouchWindow->assertNoEvents();
5635}
5636
5637/**
5638 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5639 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5640 * (which alone would result in allowing touches) does not affect the blocking behavior.
5641 */
5642TEST_F(InputDispatcherUntrustedTouchesTest,
5643 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5644 const sp<FakeWindowHandle>& wB =
5645 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5646 OPACITY_BELOW_THRESHOLD);
5647 const sp<FakeWindowHandle>& wC =
5648 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5649 OPACITY_BELOW_THRESHOLD);
5650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5651
5652 touch();
5653
5654 mTouchWindow->assertNoEvents();
5655}
5656
5657/**
5658 * This test is testing that a window from a different UID but with same application token doesn't
5659 * block the touch. Apps can share the application token for close UI collaboration for example.
5660 */
5661TEST_F(InputDispatcherUntrustedTouchesTest,
5662 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5663 const sp<FakeWindowHandle>& w =
5664 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5665 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5667
5668 touch();
5669
5670 mTouchWindow->consumeAnyMotionDown();
5671}
5672
arthurhungb89ccb02020-12-30 16:19:01 +08005673class InputDispatcherDragTests : public InputDispatcherTest {
5674protected:
5675 std::shared_ptr<FakeApplicationHandle> mApp;
5676 sp<FakeWindowHandle> mWindow;
5677 sp<FakeWindowHandle> mSecondWindow;
5678 sp<FakeWindowHandle> mDragWindow;
5679
5680 void SetUp() override {
5681 InputDispatcherTest::SetUp();
5682 mApp = std::make_shared<FakeApplicationHandle>();
5683 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5684 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005685 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005686
5687 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5688 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005689 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005690
5691 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5693 }
5694
5695 // Start performing drag, we will create a drag window and transfer touch to it.
5696 void performDrag() {
5697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5699 {50, 50}))
5700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5701
5702 // Window should receive motion event.
5703 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5704
5705 // The drag window covers the entire display
5706 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5707 mDispatcher->setInputWindows(
5708 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5709
5710 // Transfer touch focus to the drag window
5711 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5712 true /* isDragDrop */);
5713 mWindow->consumeMotionCancel();
5714 mDragWindow->consumeMotionDown();
5715 }
arthurhung6d4bed92021-03-17 11:59:33 +08005716
5717 // Start performing drag, we will create a drag window and transfer touch to it.
5718 void performStylusDrag() {
5719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5720 injectMotionEvent(mDispatcher,
5721 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5722 AINPUT_SOURCE_STYLUS)
5723 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5724 .pointer(PointerBuilder(0,
5725 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5726 .x(50)
5727 .y(50))
5728 .build()));
5729 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5730
5731 // The drag window covers the entire display
5732 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5733 mDispatcher->setInputWindows(
5734 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5735
5736 // Transfer touch focus to the drag window
5737 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5738 true /* isDragDrop */);
5739 mWindow->consumeMotionCancel();
5740 mDragWindow->consumeMotionDown();
5741 }
arthurhungb89ccb02020-12-30 16:19:01 +08005742};
5743
5744TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5745 performDrag();
5746
5747 // Move on window.
5748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5749 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5750 ADISPLAY_ID_DEFAULT, {50, 50}))
5751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5752 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5753 mWindow->consumeDragEvent(false, 50, 50);
5754 mSecondWindow->assertNoEvents();
5755
5756 // Move to another window.
5757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5758 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5759 ADISPLAY_ID_DEFAULT, {150, 50}))
5760 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5761 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5762 mWindow->consumeDragEvent(true, 150, 50);
5763 mSecondWindow->consumeDragEvent(false, 50, 50);
5764
5765 // Move back to original window.
5766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5767 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5768 ADISPLAY_ID_DEFAULT, {50, 50}))
5769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5770 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5771 mWindow->consumeDragEvent(false, 50, 50);
5772 mSecondWindow->consumeDragEvent(true, -50, 50);
5773
5774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5775 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5777 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5778 mWindow->assertNoEvents();
5779 mSecondWindow->assertNoEvents();
5780}
5781
arthurhungf452d0b2021-01-06 00:19:52 +08005782TEST_F(InputDispatcherDragTests, DragAndDrop) {
5783 performDrag();
5784
5785 // Move on window.
5786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5787 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5788 ADISPLAY_ID_DEFAULT, {50, 50}))
5789 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5790 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5791 mWindow->consumeDragEvent(false, 50, 50);
5792 mSecondWindow->assertNoEvents();
5793
5794 // Move to another window.
5795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5796 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5797 ADISPLAY_ID_DEFAULT, {150, 50}))
5798 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5799 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5800 mWindow->consumeDragEvent(true, 150, 50);
5801 mSecondWindow->consumeDragEvent(false, 50, 50);
5802
5803 // drop to another window.
5804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5805 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5806 {150, 50}))
5807 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5808 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5809 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5810 mWindow->assertNoEvents();
5811 mSecondWindow->assertNoEvents();
5812}
5813
arthurhung6d4bed92021-03-17 11:59:33 +08005814TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5815 performStylusDrag();
5816
5817 // Move on window and keep button pressed.
5818 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5819 injectMotionEvent(mDispatcher,
5820 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5821 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5822 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5823 .x(50)
5824 .y(50))
5825 .build()))
5826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5827 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5828 mWindow->consumeDragEvent(false, 50, 50);
5829 mSecondWindow->assertNoEvents();
5830
5831 // Move to another window and release button, expect to drop item.
5832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5833 injectMotionEvent(mDispatcher,
5834 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5835 .buttonState(0)
5836 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5837 .x(150)
5838 .y(50))
5839 .build()))
5840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5841 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5842 mWindow->assertNoEvents();
5843 mSecondWindow->assertNoEvents();
5844 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5845
5846 // nothing to the window.
5847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5848 injectMotionEvent(mDispatcher,
5849 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5850 .buttonState(0)
5851 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5852 .x(150)
5853 .y(50))
5854 .build()))
5855 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5856 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5857 mWindow->assertNoEvents();
5858 mSecondWindow->assertNoEvents();
5859}
5860
Arthur Hung6d0571e2021-04-09 20:18:16 +08005861TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5862 performDrag();
5863
5864 // Set second window invisible.
5865 mSecondWindow->setVisible(false);
5866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5867
5868 // Move on window.
5869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5870 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5871 ADISPLAY_ID_DEFAULT, {50, 50}))
5872 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5873 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5874 mWindow->consumeDragEvent(false, 50, 50);
5875 mSecondWindow->assertNoEvents();
5876
5877 // Move to another window.
5878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5879 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5880 ADISPLAY_ID_DEFAULT, {150, 50}))
5881 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5882 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5883 mWindow->consumeDragEvent(true, 150, 50);
5884 mSecondWindow->assertNoEvents();
5885
5886 // drop to another window.
5887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5888 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5889 {150, 50}))
5890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5891 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5892 mFakePolicy->assertDropTargetEquals(nullptr);
5893 mWindow->assertNoEvents();
5894 mSecondWindow->assertNoEvents();
5895}
5896
Vishnu Nair062a8672021-09-03 16:07:44 -07005897class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5898
5899TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5900 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5901 sp<FakeWindowHandle> window =
5902 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5903 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5904 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5905 window->setFocusable(true);
5906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5907 setFocusedWindow(window);
5908 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5909
5910 // With the flag set, window should not get any input
5911 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5912 mDispatcher->notifyKey(&keyArgs);
5913 window->assertNoEvents();
5914
5915 NotifyMotionArgs motionArgs =
5916 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5917 ADISPLAY_ID_DEFAULT);
5918 mDispatcher->notifyMotion(&motionArgs);
5919 window->assertNoEvents();
5920
5921 // With the flag cleared, the window should get input
5922 window->setInputFeatures({});
5923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5924
5925 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5926 mDispatcher->notifyKey(&keyArgs);
5927 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5928
5929 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5930 ADISPLAY_ID_DEFAULT);
5931 mDispatcher->notifyMotion(&motionArgs);
5932 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5933 window->assertNoEvents();
5934}
5935
5936TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5937 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5938 std::make_shared<FakeApplicationHandle>();
5939 sp<FakeWindowHandle> obscuringWindow =
5940 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5941 ADISPLAY_ID_DEFAULT);
5942 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5943 obscuringWindow->setOwnerInfo(111, 111);
5944 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5945 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5946 sp<FakeWindowHandle> window =
5947 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5948 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5949 window->setOwnerInfo(222, 222);
5950 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5951 window->setFocusable(true);
5952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5953 setFocusedWindow(window);
5954 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5955
5956 // With the flag set, window should not get any input
5957 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5958 mDispatcher->notifyKey(&keyArgs);
5959 window->assertNoEvents();
5960
5961 NotifyMotionArgs motionArgs =
5962 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5963 ADISPLAY_ID_DEFAULT);
5964 mDispatcher->notifyMotion(&motionArgs);
5965 window->assertNoEvents();
5966
5967 // With the flag cleared, the window should get input
5968 window->setInputFeatures({});
5969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5970
5971 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5972 mDispatcher->notifyKey(&keyArgs);
5973 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5974
5975 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5976 ADISPLAY_ID_DEFAULT);
5977 mDispatcher->notifyMotion(&motionArgs);
5978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5979 window->assertNoEvents();
5980}
5981
5982TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5983 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5984 std::make_shared<FakeApplicationHandle>();
5985 sp<FakeWindowHandle> obscuringWindow =
5986 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5987 ADISPLAY_ID_DEFAULT);
5988 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5989 obscuringWindow->setOwnerInfo(111, 111);
5990 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5991 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5992 sp<FakeWindowHandle> window =
5993 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5994 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5995 window->setOwnerInfo(222, 222);
5996 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5997 window->setFocusable(true);
5998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5999 setFocusedWindow(window);
6000 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6001
6002 // With the flag set, window should not get any input
6003 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6004 mDispatcher->notifyKey(&keyArgs);
6005 window->assertNoEvents();
6006
6007 NotifyMotionArgs motionArgs =
6008 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6009 ADISPLAY_ID_DEFAULT);
6010 mDispatcher->notifyMotion(&motionArgs);
6011 window->assertNoEvents();
6012
6013 // When the window is no longer obscured because it went on top, it should get input
6014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6015
6016 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6017 mDispatcher->notifyKey(&keyArgs);
6018 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6019
6020 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6021 ADISPLAY_ID_DEFAULT);
6022 mDispatcher->notifyMotion(&motionArgs);
6023 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6024 window->assertNoEvents();
6025}
6026
Garfield Tane84e6f92019-08-29 17:28:41 -07006027} // namespace android::inputdispatcher