blob: 1879cecb5c7c5444629cd20699934a02c82c9c9f [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 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000820 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
821 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
822 }
arthurhungb89ccb02020-12-30 16:19:01 +0800823 case AINPUT_EVENT_TYPE_DRAG: {
824 FAIL() << "Use 'consumeDragEvent' for DRAG events";
825 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826 default: {
827 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
828 }
829 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800830 }
831
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100832 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
833 InputEvent* event = consume();
834 ASSERT_NE(nullptr, event) << mName.c_str()
835 << ": consumer should have returned non-NULL event.";
836 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
837 << "Got " << inputEventTypeToString(event->getType())
838 << " event instead of FOCUS event";
839
840 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
841 << mName.c_str() << ": event displayId should always be NONE.";
842
843 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
844 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
845 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
846 }
847
Prabir Pradhan99987712020-11-10 18:43:05 -0800848 void consumeCaptureEvent(bool hasCapture) {
849 const InputEvent* event = consume();
850 ASSERT_NE(nullptr, event) << mName.c_str()
851 << ": consumer should have returned non-NULL event.";
852 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
853 << "Got " << inputEventTypeToString(event->getType())
854 << " event instead of CAPTURE event";
855
856 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
857 << mName.c_str() << ": event displayId should always be NONE.";
858
859 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
860 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
861 }
862
arthurhungb89ccb02020-12-30 16:19:01 +0800863 void consumeDragEvent(bool isExiting, float x, float y) {
864 const InputEvent* event = consume();
865 ASSERT_NE(nullptr, event) << mName.c_str()
866 << ": consumer should have returned non-NULL event.";
867 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
868 << "Got " << inputEventTypeToString(event->getType())
869 << " event instead of DRAG event";
870
871 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
872 << mName.c_str() << ": event displayId should always be NONE.";
873
874 const auto& dragEvent = static_cast<const DragEvent&>(*event);
875 EXPECT_EQ(isExiting, dragEvent.isExiting());
876 EXPECT_EQ(x, dragEvent.getX());
877 EXPECT_EQ(y, dragEvent.getY());
878 }
879
Antonio Kantekf16f2832021-09-28 04:39:20 +0000880 void consumeTouchModeEvent(bool inTouchMode) {
881 const InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of TOUCH_MODE event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
891 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
892 }
893
chaviwd1c23182019-12-20 18:44:56 -0800894 void assertNoEvents() {
895 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 if (event == nullptr) {
897 return;
898 }
899 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
900 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
901 ADD_FAILURE() << "Received key event "
902 << KeyEvent::actionToString(keyEvent.getAction());
903 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
904 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
905 ADD_FAILURE() << "Received motion event "
906 << MotionEvent::actionToString(motionEvent.getAction());
907 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
908 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
909 ADD_FAILURE() << "Received focus event, hasFocus = "
910 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800911 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
912 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
913 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
914 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000915 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
916 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
917 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
918 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919 }
920 FAIL() << mName.c_str()
921 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800922 }
923
924 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
925
926protected:
927 std::unique_ptr<InputConsumer> mConsumer;
928 PreallocatedInputEventFactory mEventFactory;
929
930 std::string mName;
931};
932
chaviw3277faf2021-05-19 16:45:23 -0500933class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800934public:
935 static const int32_t WIDTH = 600;
936 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800937
Chris Yea209fde2020-07-22 13:54:51 -0700938 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700939 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500940 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800941 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500942 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700943 base::Result<std::unique_ptr<InputChannel>> channel =
944 dispatcher->createInputChannel(name);
945 token = (*channel)->getConnectionToken();
946 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800947 }
948
949 inputApplicationHandle->updateInfo();
950 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
951
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500952 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700953 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800954 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500955 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500956 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000957 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800958 mInfo.frameLeft = 0;
959 mInfo.frameTop = 0;
960 mInfo.frameRight = WIDTH;
961 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700962 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800963 mInfo.globalScaleFactor = 1.0;
964 mInfo.touchableRegion.clear();
965 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
966 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700967 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800968 mInfo.hasWallpaper = false;
969 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800970 mInfo.ownerPid = INJECTOR_PID;
971 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800972 mInfo.displayId = displayId;
973 }
974
Arthur Hungabbb9d82021-09-01 14:52:30 +0000975 sp<FakeWindowHandle> clone(
976 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700977 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +0000978 sp<FakeWindowHandle> handle =
979 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
980 displayId, mInfo.token);
981 return handle;
982 }
983
Vishnu Nair47074b82020-08-14 11:54:47 -0700984 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800985
Vishnu Nair958da932020-08-21 17:12:37 -0700986 void setVisible(bool visible) { mInfo.visible = visible; }
987
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700988 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500989 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700990 }
991
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 void setPaused(bool paused) { mInfo.paused = paused; }
993
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000994 void setAlpha(float alpha) { mInfo.alpha = alpha; }
995
chaviw3277faf2021-05-19 16:45:23 -0500996 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000997
Bernardo Rufino7393d172021-02-26 13:56:11 +0000998 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
999
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001000 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001001 mInfo.frameLeft = frame.left;
1002 mInfo.frameTop = frame.top;
1003 mInfo.frameRight = frame.right;
1004 mInfo.frameBottom = frame.bottom;
1005 mInfo.touchableRegion.clear();
1006 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001007
1008 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1009 ui::Transform translate;
1010 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1011 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001012 }
1013
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001014 void setType(WindowInfo::Type type) { mInfo.type = type; }
1015
1016 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1017
chaviw3277faf2021-05-19 16:45:23 -05001018 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001019
chaviw3277faf2021-05-19 16:45:23 -05001020 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001021
chaviw3277faf2021-05-19 16:45:23 -05001022 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001023
chaviw9eaa22c2020-07-01 16:21:27 -07001024 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1025 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1026 }
1027
1028 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001029
yunho.shinf4a80b82020-11-16 21:13:57 +09001030 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1031
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001032 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1033 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1034 expectedFlags);
1035 }
1036
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1038 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1039 }
1040
Svet Ganov5d3bc372020-01-26 23:11:07 -08001041 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001042 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001043 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1044 expectedFlags);
1045 }
1046
1047 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001048 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001049 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1050 expectedFlags);
1051 }
1052
1053 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001054 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001055 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1056 }
1057
1058 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1059 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001060 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1061 expectedFlags);
1062 }
1063
Svet Ganov5d3bc372020-01-26 23:11:07 -08001064 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001065 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1066 int32_t expectedFlags = 0) {
1067 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1068 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001069 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1070 }
1071
1072 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001073 int32_t expectedFlags = 0) {
1074 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1075 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001076 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1077 }
1078
1079 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001080 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001081 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1082 expectedFlags);
1083 }
1084
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001085 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1086 int32_t expectedFlags = 0) {
1087 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1088 expectedFlags);
1089 }
1090
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001091 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1092 ASSERT_NE(mInputReceiver, nullptr)
1093 << "Cannot consume events from a window with no receiver";
1094 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1095 }
1096
Prabir Pradhan99987712020-11-10 18:43:05 -08001097 void consumeCaptureEvent(bool hasCapture) {
1098 ASSERT_NE(mInputReceiver, nullptr)
1099 << "Cannot consume events from a window with no receiver";
1100 mInputReceiver->consumeCaptureEvent(hasCapture);
1101 }
1102
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001103 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1104 std::optional<int32_t> expectedDisplayId,
1105 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001106 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1107 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1108 expectedFlags);
1109 }
1110
arthurhungb89ccb02020-12-30 16:19:01 +08001111 void consumeDragEvent(bool isExiting, float x, float y) {
1112 mInputReceiver->consumeDragEvent(isExiting, x, y);
1113 }
1114
Antonio Kantekf16f2832021-09-28 04:39:20 +00001115 void consumeTouchModeEvent(bool inTouchMode) {
1116 ASSERT_NE(mInputReceiver, nullptr)
1117 << "Cannot consume events from a window with no receiver";
1118 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1119 }
1120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001121 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001122 if (mInputReceiver == nullptr) {
1123 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1124 return std::nullopt;
1125 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001126 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001127 }
1128
1129 void finishEvent(uint32_t sequenceNum) {
1130 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1131 mInputReceiver->finishEvent(sequenceNum);
1132 }
1133
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001134 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1135 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1136 mInputReceiver->sendTimeline(inputEventId, timeline);
1137 }
1138
chaviwaf87b3e2019-10-01 16:59:28 -07001139 InputEvent* consume() {
1140 if (mInputReceiver == nullptr) {
1141 return nullptr;
1142 }
1143 return mInputReceiver->consume();
1144 }
1145
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001146 MotionEvent* consumeMotion() {
1147 InputEvent* event = consume();
1148 if (event == nullptr) {
1149 ADD_FAILURE() << "Consume failed : no event";
1150 return nullptr;
1151 }
1152 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1153 ADD_FAILURE() << "Instead of motion event, got "
1154 << inputEventTypeToString(event->getType());
1155 return nullptr;
1156 }
1157 return static_cast<MotionEvent*>(event);
1158 }
1159
Arthur Hungb92218b2018-08-14 12:00:21 +08001160 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001161 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001162 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001163 return; // Can't receive events if the window does not have input channel
1164 }
1165 ASSERT_NE(nullptr, mInputReceiver)
1166 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001167 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001168 }
1169
chaviwaf87b3e2019-10-01 16:59:28 -07001170 sp<IBinder> getToken() { return mInfo.token; }
1171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 const std::string& getName() { return mName; }
1173
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001174 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1175 mInfo.ownerPid = ownerPid;
1176 mInfo.ownerUid = ownerUid;
1177 }
1178
chaviwd1c23182019-12-20 18:44:56 -08001179private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001181 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001182 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001183};
1184
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001185std::atomic<int32_t> FakeWindowHandle::sId{1};
1186
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001187static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001188 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001189 int32_t displayId = ADISPLAY_ID_NONE,
1190 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001191 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1192 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001193 KeyEvent event;
1194 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1195
1196 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001197 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001198 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1199 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001200
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001201 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1202 if (!allowKeyRepeat) {
1203 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1204 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001205 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001207 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001208}
1209
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001210static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001211 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001212 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1213}
1214
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001215// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1216// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1217// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001218static InputEventInjectionResult injectKeyDownNoRepeat(
1219 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001220 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1221 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1222 /* allowKeyRepeat */ false);
1223}
1224
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001225static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001226 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001227 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1228}
1229
Garfield Tandf26e862020-07-01 20:18:19 -07001230class PointerBuilder {
1231public:
1232 PointerBuilder(int32_t id, int32_t toolType) {
1233 mProperties.clear();
1234 mProperties.id = id;
1235 mProperties.toolType = toolType;
1236 mCoords.clear();
1237 }
1238
1239 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1240
1241 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1242
1243 PointerBuilder& axis(int32_t axis, float value) {
1244 mCoords.setAxisValue(axis, value);
1245 return *this;
1246 }
1247
1248 PointerProperties buildProperties() const { return mProperties; }
1249
1250 PointerCoords buildCoords() const { return mCoords; }
1251
1252private:
1253 PointerProperties mProperties;
1254 PointerCoords mCoords;
1255};
1256
1257class MotionEventBuilder {
1258public:
1259 MotionEventBuilder(int32_t action, int32_t source) {
1260 mAction = action;
1261 mSource = source;
1262 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1263 }
1264
1265 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1266 mEventTime = eventTime;
1267 return *this;
1268 }
1269
1270 MotionEventBuilder& displayId(int32_t displayId) {
1271 mDisplayId = displayId;
1272 return *this;
1273 }
1274
1275 MotionEventBuilder& actionButton(int32_t actionButton) {
1276 mActionButton = actionButton;
1277 return *this;
1278 }
1279
arthurhung6d4bed92021-03-17 11:59:33 +08001280 MotionEventBuilder& buttonState(int32_t buttonState) {
1281 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001282 return *this;
1283 }
1284
1285 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1286 mRawXCursorPosition = rawXCursorPosition;
1287 return *this;
1288 }
1289
1290 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1291 mRawYCursorPosition = rawYCursorPosition;
1292 return *this;
1293 }
1294
1295 MotionEventBuilder& pointer(PointerBuilder pointer) {
1296 mPointers.push_back(pointer);
1297 return *this;
1298 }
1299
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001300 MotionEventBuilder& addFlag(uint32_t flags) {
1301 mFlags |= flags;
1302 return *this;
1303 }
1304
Garfield Tandf26e862020-07-01 20:18:19 -07001305 MotionEvent build() {
1306 std::vector<PointerProperties> pointerProperties;
1307 std::vector<PointerCoords> pointerCoords;
1308 for (const PointerBuilder& pointer : mPointers) {
1309 pointerProperties.push_back(pointer.buildProperties());
1310 pointerCoords.push_back(pointer.buildCoords());
1311 }
1312
1313 // Set mouse cursor position for the most common cases to avoid boilerplate.
1314 if (mSource == AINPUT_SOURCE_MOUSE &&
1315 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1316 mPointers.size() == 1) {
1317 mRawXCursorPosition = pointerCoords[0].getX();
1318 mRawYCursorPosition = pointerCoords[0].getY();
1319 }
1320
1321 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001322 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001323 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001324 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001325 mButtonState, MotionClassification::NONE, identityTransform,
1326 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001327 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1328 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001329
1330 return event;
1331 }
1332
1333private:
1334 int32_t mAction;
1335 int32_t mSource;
1336 nsecs_t mEventTime;
1337 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1338 int32_t mActionButton{0};
1339 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001340 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001341 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1342 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1343
1344 std::vector<PointerBuilder> mPointers;
1345};
1346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001347static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001348 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001349 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001350 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001351 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1352 injectionTimeout,
1353 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1354}
1355
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001356static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001357 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1358 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001359 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001360 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1361 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001362 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001363 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001364 MotionEvent event = MotionEventBuilder(action, source)
1365 .displayId(displayId)
1366 .eventTime(eventTime)
1367 .rawXCursorPosition(cursorPosition.x)
1368 .rawYCursorPosition(cursorPosition.y)
1369 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1370 .x(position.x)
1371 .y(position.y))
1372 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001373
1374 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001375 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001376}
1377
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001378static InputEventInjectionResult injectMotionDown(
1379 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1380 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001381 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001382}
1383
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001384static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001385 int32_t source, int32_t displayId,
1386 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001387 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001388}
1389
Jackal Guof9696682018-10-05 12:23:23 +08001390static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1391 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1392 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001393 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1394 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1395 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001396
1397 return args;
1398}
1399
chaviwd1c23182019-12-20 18:44:56 -08001400static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1401 const std::vector<PointF>& points) {
1402 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001403 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1404 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1405 }
1406
chaviwd1c23182019-12-20 18:44:56 -08001407 PointerProperties pointerProperties[pointerCount];
1408 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001409
chaviwd1c23182019-12-20 18:44:56 -08001410 for (size_t i = 0; i < pointerCount; i++) {
1411 pointerProperties[i].clear();
1412 pointerProperties[i].id = i;
1413 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001414
chaviwd1c23182019-12-20 18:44:56 -08001415 pointerCoords[i].clear();
1416 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1417 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1418 }
Jackal Guof9696682018-10-05 12:23:23 +08001419
1420 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1421 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001422 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001423 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1424 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001425 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1426 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001427 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1428 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001429
1430 return args;
1431}
1432
chaviwd1c23182019-12-20 18:44:56 -08001433static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1434 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1435}
1436
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001437static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1438 const PointerCaptureRequest& request) {
1439 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001440}
1441
Arthur Hungb92218b2018-08-14 12:00:21 +08001442TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001443 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001444 sp<FakeWindowHandle> window =
1445 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001446
Arthur Hung72d8dc32020-03-28 00:48:39 +00001447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001451
1452 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001453 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001454}
1455
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001456TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1457 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1458 sp<FakeWindowHandle> window =
1459 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1460
1461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1462 // Inject a MotionEvent to an unknown display.
1463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1464 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1465 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1466
1467 // Window should receive motion event.
1468 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1469}
1470
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001471/**
1472 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1473 * To ensure that window receives only events that were directly inside of it, add
1474 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1475 * when finding touched windows.
1476 * This test serves as a sanity check for the next test, where setInputWindows is
1477 * called twice.
1478 */
1479TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001480 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001481 sp<FakeWindowHandle> window =
1482 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1483 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001484 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001485
1486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1489 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001491
1492 // Window should receive motion event.
1493 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1494}
1495
1496/**
1497 * Calling setInputWindows twice, with the same info, should not cause any issues.
1498 * To ensure that window receives only events that were directly inside of it, add
1499 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1500 * when finding touched windows.
1501 */
1502TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001504 sp<FakeWindowHandle> window =
1505 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1506 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001507 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001508
1509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1513 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001515
1516 // Window should receive motion event.
1517 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1518}
1519
Arthur Hungb92218b2018-08-14 12:00:21 +08001520// The foreground window should receive the first touch down event.
1521TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001522 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001523 sp<FakeWindowHandle> windowTop =
1524 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1525 sp<FakeWindowHandle> windowSecond =
1526 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001527
Arthur Hung72d8dc32020-03-28 00:48:39 +00001528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001532
1533 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001534 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001535 windowSecond->assertNoEvents();
1536}
1537
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001538/**
1539 * Two windows: A top window, and a wallpaper behind the window.
1540 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1541 * gets ACTION_CANCEL.
1542 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1543 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1544 */
1545TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1546 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1547 sp<FakeWindowHandle> foregroundWindow =
1548 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1549 foregroundWindow->setHasWallpaper(true);
1550 sp<FakeWindowHandle> wallpaperWindow =
1551 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1552 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1553 constexpr int expectedWallpaperFlags =
1554 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1555
1556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1559 {100, 200}))
1560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1561
1562 // Both foreground window and its wallpaper should receive the touch down
1563 foregroundWindow->consumeMotionDown();
1564 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1565
1566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1567 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1568 ADISPLAY_ID_DEFAULT, {110, 200}))
1569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1570
1571 foregroundWindow->consumeMotionMove();
1572 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1573
1574 // Now the foreground window goes away, but the wallpaper stays
1575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1576 foregroundWindow->consumeMotionCancel();
1577 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1578 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1579}
1580
1581/**
1582 * A single window that receives touch (on top), and a wallpaper window underneath it.
1583 * The top window gets a multitouch gesture.
1584 * Ensure that wallpaper gets the same gesture.
1585 */
1586TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1588 sp<FakeWindowHandle> window =
1589 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1590 window->setHasWallpaper(true);
1591
1592 sp<FakeWindowHandle> wallpaperWindow =
1593 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1594 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1595 constexpr int expectedWallpaperFlags =
1596 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1597
1598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1599
1600 // Touch down on top window
1601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1602 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1603 {100, 100}))
1604 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1605
1606 // Both top window and its wallpaper should receive the touch down
1607 window->consumeMotionDown();
1608 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1609
1610 // Second finger down on the top window
1611 const MotionEvent secondFingerDownEvent =
1612 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1613 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1614 AINPUT_SOURCE_TOUCHSCREEN)
1615 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1616 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1617 .x(100)
1618 .y(100))
1619 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1620 .x(150)
1621 .y(150))
1622 .build();
1623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1624 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1625 InputEventInjectionSync::WAIT_FOR_RESULT))
1626 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1627
1628 window->consumeMotionPointerDown(1 /* pointerIndex */);
1629 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1630 expectedWallpaperFlags);
1631 window->assertNoEvents();
1632 wallpaperWindow->assertNoEvents();
1633}
1634
1635/**
1636 * Two windows: a window on the left and window on the right.
1637 * A third window, wallpaper, is behind both windows, and spans both top windows.
1638 * The first touch down goes to the left window. A second pointer touches down on the right window.
1639 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1640 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1641 * ACTION_POINTER_DOWN(1).
1642 */
1643TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1645 sp<FakeWindowHandle> leftWindow =
1646 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1647 leftWindow->setFrame(Rect(0, 0, 200, 200));
1648 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1649 leftWindow->setHasWallpaper(true);
1650
1651 sp<FakeWindowHandle> rightWindow =
1652 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1653 rightWindow->setFrame(Rect(200, 0, 400, 200));
1654 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1655 rightWindow->setHasWallpaper(true);
1656
1657 sp<FakeWindowHandle> wallpaperWindow =
1658 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1659 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1660 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1661 constexpr int expectedWallpaperFlags =
1662 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1663
1664 mDispatcher->setInputWindows(
1665 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1666
1667 // Touch down on left window
1668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1669 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1670 {100, 100}))
1671 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1672
1673 // Both foreground window and its wallpaper should receive the touch down
1674 leftWindow->consumeMotionDown();
1675 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1676
1677 // Second finger down on the right window
1678 const MotionEvent secondFingerDownEvent =
1679 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1680 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1681 AINPUT_SOURCE_TOUCHSCREEN)
1682 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1683 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1684 .x(100)
1685 .y(100))
1686 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1687 .x(300)
1688 .y(100))
1689 .build();
1690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1691 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1692 InputEventInjectionSync::WAIT_FOR_RESULT))
1693 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1694
1695 leftWindow->consumeMotionMove();
1696 // Since the touch is split, right window gets ACTION_DOWN
1697 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1698 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1699 expectedWallpaperFlags);
1700
1701 // Now, leftWindow, which received the first finger, disappears.
1702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1703 leftWindow->consumeMotionCancel();
1704 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1705 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1706
1707 // The pointer that's still down on the right window moves, and goes to the right window only.
1708 // As far as the dispatcher's concerned though, both pointers are still present.
1709 const MotionEvent secondFingerMoveEvent =
1710 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1711 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1712 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1713 .x(100)
1714 .y(100))
1715 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1716 .x(310)
1717 .y(110))
1718 .build();
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1721 InputEventInjectionSync::WAIT_FOR_RESULT));
1722 rightWindow->consumeMotionMove();
1723
1724 leftWindow->assertNoEvents();
1725 rightWindow->assertNoEvents();
1726 wallpaperWindow->assertNoEvents();
1727}
1728
Garfield Tandf26e862020-07-01 20:18:19 -07001729TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001730 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001731 sp<FakeWindowHandle> windowLeft =
1732 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1733 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001734 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001735 sp<FakeWindowHandle> windowRight =
1736 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1737 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001738 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001739
1740 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1741
1742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1743
1744 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001746 injectMotionEvent(mDispatcher,
1747 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1748 AINPUT_SOURCE_MOUSE)
1749 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1750 .x(900)
1751 .y(400))
1752 .build()));
1753 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1754 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1755 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1756 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1757
1758 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001760 injectMotionEvent(mDispatcher,
1761 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1762 AINPUT_SOURCE_MOUSE)
1763 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1764 .x(300)
1765 .y(400))
1766 .build()));
1767 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1768 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1769 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1770 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1771 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1772 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1773
1774 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001776 injectMotionEvent(mDispatcher,
1777 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1778 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1779 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1780 .x(300)
1781 .y(400))
1782 .build()));
1783 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1784
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001786 injectMotionEvent(mDispatcher,
1787 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1788 AINPUT_SOURCE_MOUSE)
1789 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1790 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1791 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1792 .x(300)
1793 .y(400))
1794 .build()));
1795 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1796 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1797
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001799 injectMotionEvent(mDispatcher,
1800 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1801 AINPUT_SOURCE_MOUSE)
1802 .buttonState(0)
1803 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1804 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1805 .x(300)
1806 .y(400))
1807 .build()));
1808 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1809 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1810
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001812 injectMotionEvent(mDispatcher,
1813 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1814 .buttonState(0)
1815 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1816 .x(300)
1817 .y(400))
1818 .build()));
1819 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1820
1821 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001823 injectMotionEvent(mDispatcher,
1824 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1825 AINPUT_SOURCE_MOUSE)
1826 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1827 .x(900)
1828 .y(400))
1829 .build()));
1830 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1831 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1832 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1833 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1834 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1835 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1836}
1837
1838// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1839// directly in this test.
1840TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001841 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001842 sp<FakeWindowHandle> window =
1843 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1844 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001845 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001846
1847 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1848
1849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001852 injectMotionEvent(mDispatcher,
1853 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1854 AINPUT_SOURCE_MOUSE)
1855 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1856 .x(300)
1857 .y(400))
1858 .build()));
1859 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1860 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1861
1862 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001864 injectMotionEvent(mDispatcher,
1865 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1866 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1867 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1868 .x(300)
1869 .y(400))
1870 .build()));
1871 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1872
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001874 injectMotionEvent(mDispatcher,
1875 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1876 AINPUT_SOURCE_MOUSE)
1877 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1878 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1879 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1880 .x(300)
1881 .y(400))
1882 .build()));
1883 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1884 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001887 injectMotionEvent(mDispatcher,
1888 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1889 AINPUT_SOURCE_MOUSE)
1890 .buttonState(0)
1891 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1892 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1893 .x(300)
1894 .y(400))
1895 .build()));
1896 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1897 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1898
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001900 injectMotionEvent(mDispatcher,
1901 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1902 .buttonState(0)
1903 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1904 .x(300)
1905 .y(400))
1906 .build()));
1907 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1908
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001910 injectMotionEvent(mDispatcher,
1911 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1912 AINPUT_SOURCE_MOUSE)
1913 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1914 .x(300)
1915 .y(400))
1916 .build()));
1917 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1918 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1919}
1920
Garfield Tan00f511d2019-06-12 16:55:40 -07001921TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001922 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001923
1924 sp<FakeWindowHandle> windowLeft =
1925 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1926 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001927 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001928 sp<FakeWindowHandle> windowRight =
1929 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1930 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001931 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001932
1933 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1934
Arthur Hung72d8dc32020-03-28 00:48:39 +00001935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001936
1937 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1938 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001940 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001941 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001942 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001943 windowRight->assertNoEvents();
1944}
1945
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001946TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001947 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001948 sp<FakeWindowHandle> window =
1949 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001950 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001951
Arthur Hung72d8dc32020-03-28 00:48:39 +00001952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001953 setFocusedWindow(window);
1954
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001955 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001956
1957 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1958 mDispatcher->notifyKey(&keyArgs);
1959
1960 // Window should receive key down event.
1961 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1962
1963 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1964 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001965 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001966 mDispatcher->notifyDeviceReset(&args);
1967 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1968 AKEY_EVENT_FLAG_CANCELED);
1969}
1970
1971TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001972 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001973 sp<FakeWindowHandle> window =
1974 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1975
Arthur Hung72d8dc32020-03-28 00:48:39 +00001976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001977
1978 NotifyMotionArgs motionArgs =
1979 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1980 ADISPLAY_ID_DEFAULT);
1981 mDispatcher->notifyMotion(&motionArgs);
1982
1983 // Window should receive motion down event.
1984 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1985
1986 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1987 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001988 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001989 mDispatcher->notifyDeviceReset(&args);
1990 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1991 0 /*expectedFlags*/);
1992}
1993
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001994/**
1995 * Ensure the correct coordinate spaces are used by InputDispatcher.
1996 *
1997 * InputDispatcher works in the display space, so its coordinate system is relative to the display
1998 * panel. Windows get events in the window space, and get raw coordinates in the logical display
1999 * space.
2000 */
2001class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2002public:
2003 void SetUp() override {
2004 InputDispatcherTest::SetUp();
2005 mDisplayInfos.clear();
2006 mWindowInfos.clear();
2007 }
2008
2009 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2010 gui::DisplayInfo info;
2011 info.displayId = displayId;
2012 info.transform = transform;
2013 mDisplayInfos.push_back(std::move(info));
2014 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2015 }
2016
2017 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2018 mWindowInfos.push_back(*windowHandle->getInfo());
2019 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2020 }
2021
2022 // Set up a test scenario where the display has a scaled projection and there are two windows
2023 // on the display.
2024 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2025 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2026 // respectively.
2027 ui::Transform displayTransform;
2028 displayTransform.set(2, 0, 0, 4);
2029 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2030
2031 std::shared_ptr<FakeApplicationHandle> application =
2032 std::make_shared<FakeApplicationHandle>();
2033
2034 // Add two windows to the display. Their frames are represented in the display space.
2035 sp<FakeWindowHandle> firstWindow =
2036 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2037 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2038 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2039 addWindow(firstWindow);
2040
2041 sp<FakeWindowHandle> secondWindow =
2042 new FakeWindowHandle(application, mDispatcher, "Second Window",
2043 ADISPLAY_ID_DEFAULT);
2044 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2045 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2046 addWindow(secondWindow);
2047 return {std::move(firstWindow), std::move(secondWindow)};
2048 }
2049
2050private:
2051 std::vector<gui::DisplayInfo> mDisplayInfos;
2052 std::vector<gui::WindowInfo> mWindowInfos;
2053};
2054
2055TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2056 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2057 // Send down to the first window. The point is represented in the display space. The point is
2058 // selected so that if the hit test was done with the transform applied to it, then it would
2059 // end up in the incorrect window.
2060 NotifyMotionArgs downMotionArgs =
2061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2062 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2063 mDispatcher->notifyMotion(&downMotionArgs);
2064
2065 firstWindow->consumeMotionDown();
2066 secondWindow->assertNoEvents();
2067}
2068
2069// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2070// the event should be treated as being in the logical display space.
2071TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2072 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2073 // Send down to the first window. The point is represented in the logical display space. The
2074 // point is selected so that if the hit test was done in logical display space, then it would
2075 // end up in the incorrect window.
2076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2077 PointF{75 * 2, 55 * 4});
2078
2079 firstWindow->consumeMotionDown();
2080 secondWindow->assertNoEvents();
2081}
2082
2083TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2084 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2085
2086 // Send down to the second window.
2087 NotifyMotionArgs downMotionArgs =
2088 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2089 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2090 mDispatcher->notifyMotion(&downMotionArgs);
2091
2092 firstWindow->assertNoEvents();
2093 const MotionEvent* event = secondWindow->consumeMotion();
2094 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2095
2096 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2097 EXPECT_EQ(300, event->getRawX(0));
2098 EXPECT_EQ(880, event->getRawY(0));
2099
2100 // Ensure that the x and y values are in the window's coordinate space.
2101 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2102 // the logical display space. This will be the origin of the window space.
2103 EXPECT_EQ(100, event->getX(0));
2104 EXPECT_EQ(80, event->getY(0));
2105}
2106
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002107using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2108 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002109
2110class TransferTouchFixture : public InputDispatcherTest,
2111 public ::testing::WithParamInterface<TransferFunction> {};
2112
2113TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002114 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002115
2116 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002117 sp<FakeWindowHandle> firstWindow =
2118 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2119 sp<FakeWindowHandle> secondWindow =
2120 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002121
2122 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002124
2125 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002126 NotifyMotionArgs downMotionArgs =
2127 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2128 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002129 mDispatcher->notifyMotion(&downMotionArgs);
2130 // Only the first window should get the down event
2131 firstWindow->consumeMotionDown();
2132 secondWindow->assertNoEvents();
2133
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002134 // Transfer touch to the second window
2135 TransferFunction f = GetParam();
2136 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2137 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002138 // The first window gets cancel and the second gets down
2139 firstWindow->consumeMotionCancel();
2140 secondWindow->consumeMotionDown();
2141
2142 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002143 NotifyMotionArgs upMotionArgs =
2144 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2145 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002146 mDispatcher->notifyMotion(&upMotionArgs);
2147 // The first window gets no events and the second gets up
2148 firstWindow->assertNoEvents();
2149 secondWindow->consumeMotionUp();
2150}
2151
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002152TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002153 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002154
2155 PointF touchPoint = {10, 10};
2156
2157 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002158 sp<FakeWindowHandle> firstWindow =
2159 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2160 sp<FakeWindowHandle> secondWindow =
2161 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002162
2163 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002165
2166 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002167 NotifyMotionArgs downMotionArgs =
2168 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2169 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002170 mDispatcher->notifyMotion(&downMotionArgs);
2171 // Only the first window should get the down event
2172 firstWindow->consumeMotionDown();
2173 secondWindow->assertNoEvents();
2174
2175 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002176 NotifyMotionArgs pointerDownMotionArgs =
2177 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2178 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2179 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2180 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002181 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2182 // Only the first window should get the pointer down event
2183 firstWindow->consumeMotionPointerDown(1);
2184 secondWindow->assertNoEvents();
2185
2186 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002187 TransferFunction f = GetParam();
2188 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2189 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002190 // The first window gets cancel and the second gets down and pointer down
2191 firstWindow->consumeMotionCancel();
2192 secondWindow->consumeMotionDown();
2193 secondWindow->consumeMotionPointerDown(1);
2194
2195 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002196 NotifyMotionArgs pointerUpMotionArgs =
2197 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2198 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2199 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2200 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002201 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2202 // The first window gets nothing and the second gets pointer up
2203 firstWindow->assertNoEvents();
2204 secondWindow->consumeMotionPointerUp(1);
2205
2206 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002207 NotifyMotionArgs upMotionArgs =
2208 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2209 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002210 mDispatcher->notifyMotion(&upMotionArgs);
2211 // The first window gets nothing and the second gets up
2212 firstWindow->assertNoEvents();
2213 secondWindow->consumeMotionUp();
2214}
2215
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002216// For the cases of single pointer touch and two pointers non-split touch, the api's
2217// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2218// for the case where there are multiple pointers split across several windows.
2219INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2220 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002221 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2222 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002223 return dispatcher->transferTouch(destChannelToken);
2224 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002225 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2226 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002227 return dispatcher->transferTouchFocus(from, to,
2228 false /*isDragAndDrop*/);
2229 }));
2230
Svet Ganov5d3bc372020-01-26 23:11:07 -08002231TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002232 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002233
2234 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002235 sp<FakeWindowHandle> firstWindow =
2236 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002237 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002238 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002239
2240 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002241 sp<FakeWindowHandle> secondWindow =
2242 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002243 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002244 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002245
2246 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002248
2249 PointF pointInFirst = {300, 200};
2250 PointF pointInSecond = {300, 600};
2251
2252 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002253 NotifyMotionArgs firstDownMotionArgs =
2254 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2255 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002256 mDispatcher->notifyMotion(&firstDownMotionArgs);
2257 // Only the first window should get the down event
2258 firstWindow->consumeMotionDown();
2259 secondWindow->assertNoEvents();
2260
2261 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002262 NotifyMotionArgs secondDownMotionArgs =
2263 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2264 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2265 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2266 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002267 mDispatcher->notifyMotion(&secondDownMotionArgs);
2268 // The first window gets a move and the second a down
2269 firstWindow->consumeMotionMove();
2270 secondWindow->consumeMotionDown();
2271
2272 // Transfer touch focus to the second window
2273 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2274 // The first window gets cancel and the new gets pointer down (it already saw down)
2275 firstWindow->consumeMotionCancel();
2276 secondWindow->consumeMotionPointerDown(1);
2277
2278 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002279 NotifyMotionArgs pointerUpMotionArgs =
2280 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2281 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2282 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2283 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002284 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2285 // The first window gets nothing and the second gets pointer up
2286 firstWindow->assertNoEvents();
2287 secondWindow->consumeMotionPointerUp(1);
2288
2289 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002290 NotifyMotionArgs upMotionArgs =
2291 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2292 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002293 mDispatcher->notifyMotion(&upMotionArgs);
2294 // The first window gets nothing and the second gets up
2295 firstWindow->assertNoEvents();
2296 secondWindow->consumeMotionUp();
2297}
2298
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002299// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2300// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2301// touch is not supported, so the touch should continue on those windows and the transferred-to
2302// window should get nothing.
2303TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2305
2306 // Create a non touch modal window that supports split touch
2307 sp<FakeWindowHandle> firstWindow =
2308 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2309 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002310 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002311
2312 // Create a non touch modal window that supports split touch
2313 sp<FakeWindowHandle> secondWindow =
2314 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2315 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002316 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002317
2318 // Add the windows to the dispatcher
2319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2320
2321 PointF pointInFirst = {300, 200};
2322 PointF pointInSecond = {300, 600};
2323
2324 // Send down to the first window
2325 NotifyMotionArgs firstDownMotionArgs =
2326 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2327 ADISPLAY_ID_DEFAULT, {pointInFirst});
2328 mDispatcher->notifyMotion(&firstDownMotionArgs);
2329 // Only the first window should get the down event
2330 firstWindow->consumeMotionDown();
2331 secondWindow->assertNoEvents();
2332
2333 // Send down to the second window
2334 NotifyMotionArgs secondDownMotionArgs =
2335 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2336 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2337 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2338 {pointInFirst, pointInSecond});
2339 mDispatcher->notifyMotion(&secondDownMotionArgs);
2340 // The first window gets a move and the second a down
2341 firstWindow->consumeMotionMove();
2342 secondWindow->consumeMotionDown();
2343
2344 // Transfer touch focus to the second window
2345 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2346 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2347 ASSERT_FALSE(transferred);
2348 firstWindow->assertNoEvents();
2349 secondWindow->assertNoEvents();
2350
2351 // The rest of the dispatch should proceed as normal
2352 // Send pointer up to the second window
2353 NotifyMotionArgs pointerUpMotionArgs =
2354 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2355 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2356 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2357 {pointInFirst, pointInSecond});
2358 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2359 // The first window gets MOVE and the second gets pointer up
2360 firstWindow->consumeMotionMove();
2361 secondWindow->consumeMotionUp();
2362
2363 // Send up event to the first window
2364 NotifyMotionArgs upMotionArgs =
2365 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2366 ADISPLAY_ID_DEFAULT);
2367 mDispatcher->notifyMotion(&upMotionArgs);
2368 // The first window gets nothing and the second gets up
2369 firstWindow->consumeMotionUp();
2370 secondWindow->assertNoEvents();
2371}
2372
Arthur Hungabbb9d82021-09-01 14:52:30 +00002373// This case will create two windows and one mirrored window on the default display and mirror
2374// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2375// the windows info of second display before default display.
2376TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2377 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2378 sp<FakeWindowHandle> firstWindowInPrimary =
2379 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2380 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2381 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2382 sp<FakeWindowHandle> secondWindowInPrimary =
2383 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2384 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2385 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2386
2387 sp<FakeWindowHandle> mirrorWindowInPrimary =
2388 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2389 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2390 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2391
2392 sp<FakeWindowHandle> firstWindowInSecondary =
2393 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2394 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2395 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2396
2397 sp<FakeWindowHandle> secondWindowInSecondary =
2398 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2399 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2400 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2401
2402 // Update window info, let it find window handle of second display first.
2403 mDispatcher->setInputWindows(
2404 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2405 {ADISPLAY_ID_DEFAULT,
2406 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2407
2408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2410 {50, 50}))
2411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2412
2413 // Window should receive motion event.
2414 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2415
2416 // Transfer touch focus
2417 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2418 secondWindowInPrimary->getToken()));
2419 // The first window gets cancel.
2420 firstWindowInPrimary->consumeMotionCancel();
2421 secondWindowInPrimary->consumeMotionDown();
2422
2423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2424 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2425 ADISPLAY_ID_DEFAULT, {150, 50}))
2426 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2427 firstWindowInPrimary->assertNoEvents();
2428 secondWindowInPrimary->consumeMotionMove();
2429
2430 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2431 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2432 {150, 50}))
2433 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2434 firstWindowInPrimary->assertNoEvents();
2435 secondWindowInPrimary->consumeMotionUp();
2436}
2437
2438// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2439// 'transferTouch' api.
2440TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2441 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2442 sp<FakeWindowHandle> firstWindowInPrimary =
2443 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2444 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2445 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2446 sp<FakeWindowHandle> secondWindowInPrimary =
2447 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2448 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2449 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2450
2451 sp<FakeWindowHandle> mirrorWindowInPrimary =
2452 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2453 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2454 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2455
2456 sp<FakeWindowHandle> firstWindowInSecondary =
2457 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2458 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2459 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2460
2461 sp<FakeWindowHandle> secondWindowInSecondary =
2462 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2463 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2464 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2465
2466 // Update window info, let it find window handle of second display first.
2467 mDispatcher->setInputWindows(
2468 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2469 {ADISPLAY_ID_DEFAULT,
2470 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2471
2472 // Touch on second display.
2473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2474 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2476
2477 // Window should receive motion event.
2478 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2479
2480 // Transfer touch focus
2481 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2482
2483 // The first window gets cancel.
2484 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2485 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2486
2487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2488 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2489 SECOND_DISPLAY_ID, {150, 50}))
2490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2491 firstWindowInPrimary->assertNoEvents();
2492 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2493
2494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2495 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2497 firstWindowInPrimary->assertNoEvents();
2498 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2499}
2500
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002501TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002502 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002503 sp<FakeWindowHandle> window =
2504 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2505
Vishnu Nair47074b82020-08-14 11:54:47 -07002506 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002508 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002509
2510 window->consumeFocusEvent(true);
2511
2512 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2513 mDispatcher->notifyKey(&keyArgs);
2514
2515 // Window should receive key down event.
2516 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2517}
2518
2519TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002520 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002521 sp<FakeWindowHandle> window =
2522 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2523
Arthur Hung72d8dc32020-03-28 00:48:39 +00002524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002525
2526 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2527 mDispatcher->notifyKey(&keyArgs);
2528 mDispatcher->waitForIdle();
2529
2530 window->assertNoEvents();
2531}
2532
2533// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2534TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002536 sp<FakeWindowHandle> window =
2537 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2538
Arthur Hung72d8dc32020-03-28 00:48:39 +00002539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002540
2541 // Send key
2542 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2543 mDispatcher->notifyKey(&keyArgs);
2544 // Send motion
2545 NotifyMotionArgs motionArgs =
2546 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2547 ADISPLAY_ID_DEFAULT);
2548 mDispatcher->notifyMotion(&motionArgs);
2549
2550 // Window should receive only the motion event
2551 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2552 window->assertNoEvents(); // Key event or focus event will not be received
2553}
2554
arthurhungea3f4fc2020-12-21 23:18:53 +08002555TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2556 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2557
2558 // Create first non touch modal window that supports split touch
2559 sp<FakeWindowHandle> firstWindow =
2560 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2561 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002562 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002563
2564 // Create second non touch modal window that supports split touch
2565 sp<FakeWindowHandle> secondWindow =
2566 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2567 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002568 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002569
2570 // Add the windows to the dispatcher
2571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2572
2573 PointF pointInFirst = {300, 200};
2574 PointF pointInSecond = {300, 600};
2575
2576 // Send down to the first window
2577 NotifyMotionArgs firstDownMotionArgs =
2578 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2579 ADISPLAY_ID_DEFAULT, {pointInFirst});
2580 mDispatcher->notifyMotion(&firstDownMotionArgs);
2581 // Only the first window should get the down event
2582 firstWindow->consumeMotionDown();
2583 secondWindow->assertNoEvents();
2584
2585 // Send down to the second window
2586 NotifyMotionArgs secondDownMotionArgs =
2587 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2588 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2589 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2590 {pointInFirst, pointInSecond});
2591 mDispatcher->notifyMotion(&secondDownMotionArgs);
2592 // The first window gets a move and the second a down
2593 firstWindow->consumeMotionMove();
2594 secondWindow->consumeMotionDown();
2595
2596 // Send pointer cancel to the second window
2597 NotifyMotionArgs pointerUpMotionArgs =
2598 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2599 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2600 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2601 {pointInFirst, pointInSecond});
2602 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2603 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2604 // The first window gets move and the second gets cancel.
2605 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2606 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2607
2608 // Send up event.
2609 NotifyMotionArgs upMotionArgs =
2610 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2611 ADISPLAY_ID_DEFAULT);
2612 mDispatcher->notifyMotion(&upMotionArgs);
2613 // The first window gets up and the second gets nothing.
2614 firstWindow->consumeMotionUp();
2615 secondWindow->assertNoEvents();
2616}
2617
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002618TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2620
2621 sp<FakeWindowHandle> window =
2622 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2624 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2625 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2626 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2627
2628 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2629 window->assertNoEvents();
2630 mDispatcher->waitForIdle();
2631}
2632
chaviwd1c23182019-12-20 18:44:56 -08002633class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002634public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002635 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002636 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002637 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002638 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002639 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002640 }
2641
chaviwd1c23182019-12-20 18:44:56 -08002642 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2643
2644 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2645 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2646 expectedDisplayId, expectedFlags);
2647 }
2648
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002649 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2650
2651 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2652
chaviwd1c23182019-12-20 18:44:56 -08002653 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2654 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2655 expectedDisplayId, expectedFlags);
2656 }
2657
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002658 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2659 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2660 expectedDisplayId, expectedFlags);
2661 }
2662
chaviwd1c23182019-12-20 18:44:56 -08002663 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2664 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2665 expectedDisplayId, expectedFlags);
2666 }
2667
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002668 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2669 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2670 expectedDisplayId, expectedFlags);
2671 }
2672
Evan Rosky84f07f02021-04-16 10:42:42 -07002673 MotionEvent* consumeMotion() {
2674 InputEvent* event = mInputReceiver->consume();
2675 if (!event) {
2676 ADD_FAILURE() << "No event was produced";
2677 return nullptr;
2678 }
2679 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2680 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2681 return nullptr;
2682 }
2683 return static_cast<MotionEvent*>(event);
2684 }
2685
chaviwd1c23182019-12-20 18:44:56 -08002686 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2687
2688private:
2689 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002690};
2691
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002692/**
2693 * Two entities that receive touch: A window, and a global monitor.
2694 * The touch goes to the window, and then the window disappears.
2695 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2696 * for the monitor, as well.
2697 * 1. foregroundWindow
2698 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2699 */
2700TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2702 sp<FakeWindowHandle> window =
2703 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2704
2705 FakeMonitorReceiver monitor =
2706 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2707 false /*isGestureMonitor*/);
2708
2709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2711 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2712 {100, 200}))
2713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2714
2715 // Both the foreground window and the global monitor should receive the touch down
2716 window->consumeMotionDown();
2717 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2718
2719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2720 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2721 ADISPLAY_ID_DEFAULT, {110, 200}))
2722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2723
2724 window->consumeMotionMove();
2725 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2726
2727 // Now the foreground window goes away
2728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2729 window->consumeMotionCancel();
2730 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2731
2732 // If more events come in, there will be no more foreground window to send them to. This will
2733 // cause a cancel for the monitor, as well.
2734 ASSERT_EQ(InputEventInjectionResult::FAILED,
2735 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2736 ADISPLAY_ID_DEFAULT, {120, 200}))
2737 << "Injection should fail because the window was removed";
2738 window->assertNoEvents();
2739 // Global monitor now gets the cancel
2740 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2741}
2742
Michael Wright3a240c42019-12-10 20:53:41 +00002743// Tests for gesture monitors
2744TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002745 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002746 sp<FakeWindowHandle> window =
2747 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002749
chaviwd1c23182019-12-20 18:44:56 -08002750 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2751 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002756 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002757 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002758}
2759
2760TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002762 sp<FakeWindowHandle> window =
2763 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2764
2765 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002766 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002767
Arthur Hung72d8dc32020-03-28 00:48:39 +00002768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002769 setFocusedWindow(window);
2770
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002772
chaviwd1c23182019-12-20 18:44:56 -08002773 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2774 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002775
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2777 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002778 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002779 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002780}
2781
2782TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002783 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002784 sp<FakeWindowHandle> window =
2785 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002787
chaviwd1c23182019-12-20 18:44:56 -08002788 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2789 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002792 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002794 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002795 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002796
2797 window->releaseChannel();
2798
chaviwd1c23182019-12-20 18:44:56 -08002799 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002800
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002802 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002803 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002804 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002805}
2806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002807TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2808 FakeMonitorReceiver monitor =
2809 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2810 true /*isGestureMonitor*/);
2811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002813 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2814 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2815 ASSERT_TRUE(consumeSeq);
2816
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002817 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002818 monitor.finishEvent(*consumeSeq);
2819 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002820 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002821}
2822
Evan Rosky84f07f02021-04-16 10:42:42 -07002823// Tests for gesture monitors
2824TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2825 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2826 sp<FakeWindowHandle> window =
2827 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2829 window->setWindowOffset(20, 40);
2830 window->setWindowTransform(0, 1, -1, 0);
2831
2832 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2833 true /*isGestureMonitor*/);
2834
2835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2836 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2837 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2838 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2839 MotionEvent* event = monitor.consumeMotion();
2840 // Even though window has transform, gesture monitor must not.
2841 ASSERT_EQ(ui::Transform(), event->getTransform());
2842}
2843
chaviw81e2bb92019-12-18 15:03:51 -08002844TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002845 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002846 sp<FakeWindowHandle> window =
2847 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2848
Arthur Hung72d8dc32020-03-28 00:48:39 +00002849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002850
2851 NotifyMotionArgs motionArgs =
2852 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2853 ADISPLAY_ID_DEFAULT);
2854
2855 mDispatcher->notifyMotion(&motionArgs);
2856 // Window should receive motion down event.
2857 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2858
2859 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002860 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002861 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2862 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2863 motionArgs.pointerCoords[0].getX() - 10);
2864
2865 mDispatcher->notifyMotion(&motionArgs);
2866 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2867 0 /*expectedFlags*/);
2868}
2869
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002870/**
2871 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2872 * the device default right away. In the test scenario, we check both the default value,
2873 * and the action of enabling / disabling.
2874 */
2875TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002876 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002877 sp<FakeWindowHandle> window =
2878 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2879
2880 // Set focused application.
2881 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002882 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002883
2884 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002886 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002887 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2888
2889 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002890 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002892 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2893
2894 SCOPED_TRACE("Disable touch mode");
2895 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002896 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002897 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002899 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002900 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2901
2902 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002903 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002905 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2906
2907 SCOPED_TRACE("Enable touch mode again");
2908 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002909 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002910 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002912 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002913 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2914
2915 window->assertNoEvents();
2916}
2917
Gang Wange9087892020-01-07 12:17:14 -05002918TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002919 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002920 sp<FakeWindowHandle> window =
2921 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2922
2923 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002924 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002925
Arthur Hung72d8dc32020-03-28 00:48:39 +00002926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002927 setFocusedWindow(window);
2928
Gang Wange9087892020-01-07 12:17:14 -05002929 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2930
2931 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2932 mDispatcher->notifyKey(&keyArgs);
2933
2934 InputEvent* event = window->consume();
2935 ASSERT_NE(event, nullptr);
2936
2937 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2938 ASSERT_NE(verified, nullptr);
2939 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2940
2941 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2942 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2943 ASSERT_EQ(keyArgs.source, verified->source);
2944 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2945
2946 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2947
2948 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2949 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002950 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2951 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2952 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2953 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2954 ASSERT_EQ(0, verifiedKey.repeatCount);
2955}
2956
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002957TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002958 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002959 sp<FakeWindowHandle> window =
2960 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2961
2962 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2963
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002964 ui::Transform transform;
2965 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
2966
2967 gui::DisplayInfo displayInfo;
2968 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
2969 displayInfo.transform = transform;
2970
2971 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002972
2973 NotifyMotionArgs motionArgs =
2974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2975 ADISPLAY_ID_DEFAULT);
2976 mDispatcher->notifyMotion(&motionArgs);
2977
2978 InputEvent* event = window->consume();
2979 ASSERT_NE(event, nullptr);
2980
2981 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2982 ASSERT_NE(verified, nullptr);
2983 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2984
2985 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2986 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2987 EXPECT_EQ(motionArgs.source, verified->source);
2988 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2989
2990 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2991
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002992 const vec2 rawXY =
2993 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
2994 motionArgs.pointerCoords[0].getXYValue());
2995 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
2996 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002997 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2998 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2999 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3000 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3001 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3002}
3003
Prabir Pradhan664834b2021-05-20 16:00:42 -07003004TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09003005 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3006 sp<FakeWindowHandle> window =
3007 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3008 const std::string name = window->getName();
3009
3010 // Window gets transformed by offset values.
3011 window->setWindowOffset(500.0f, 500.0f);
3012
3013 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3014 window->setFocusable(true);
3015
3016 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3017
3018 // First, we set focused window so that focusedWindowHandle is not null.
3019 setFocusedWindow(window);
3020
3021 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
3022 window->consumeFocusEvent(true);
3023
Prabir Pradhan664834b2021-05-20 16:00:42 -07003024 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
3025 AMOTION_EVENT_ACTION_DOWN),
3026 std::pair(AINPUT_SOURCE_JOYSTICK,
3027 AMOTION_EVENT_ACTION_MOVE)};
3028 for (const auto& [source, action] : nonTransformedSources) {
3029 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08003030 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09003031
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003032 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08003033 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09003034
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003035 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07003036 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08003037 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09003038
Prabir Pradhanbd527712021-03-09 19:17:09 -08003039 float expectedX = motionArgs.pointerCoords[0].getX();
3040 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09003041
Prabir Pradhanbd527712021-03-09 19:17:09 -08003042 // Ensure the axis values from the final motion event are not transformed.
3043 EXPECT_EQ(expectedX, motionEvent.getX(0))
3044 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
3045 << motionEvent.getX(0);
3046 EXPECT_EQ(expectedY, motionEvent.getY(0))
3047 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
3048 << motionEvent.getY(0);
3049 // Ensure the raw and transformed axis values for the motion event are the same.
3050 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
3051 << "expected raw and transformed X-axis values to be equal";
3052 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
3053 << "expected raw and transformed Y-axis values to be equal";
3054 }
yunho.shinf4a80b82020-11-16 21:13:57 +09003055}
3056
chaviw09c8d2d2020-08-24 15:48:26 -07003057/**
3058 * Ensure that separate calls to sign the same data are generating the same key.
3059 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3060 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3061 * tests.
3062 */
3063TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3064 KeyEvent event = getTestKeyEvent();
3065 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3066
3067 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3068 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3069 ASSERT_EQ(hmac1, hmac2);
3070}
3071
3072/**
3073 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3074 */
3075TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3076 KeyEvent event = getTestKeyEvent();
3077 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3078 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3079
3080 verifiedEvent.deviceId += 1;
3081 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3082
3083 verifiedEvent.source += 1;
3084 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3085
3086 verifiedEvent.eventTimeNanos += 1;
3087 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3088
3089 verifiedEvent.displayId += 1;
3090 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3091
3092 verifiedEvent.action += 1;
3093 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3094
3095 verifiedEvent.downTimeNanos += 1;
3096 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3097
3098 verifiedEvent.flags += 1;
3099 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3100
3101 verifiedEvent.keyCode += 1;
3102 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3103
3104 verifiedEvent.scanCode += 1;
3105 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3106
3107 verifiedEvent.metaState += 1;
3108 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3109
3110 verifiedEvent.repeatCount += 1;
3111 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3112}
3113
Vishnu Nair958da932020-08-21 17:12:37 -07003114TEST_F(InputDispatcherTest, SetFocusedWindow) {
3115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3116 sp<FakeWindowHandle> windowTop =
3117 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3118 sp<FakeWindowHandle> windowSecond =
3119 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3120 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3121
3122 // Top window is also focusable but is not granted focus.
3123 windowTop->setFocusable(true);
3124 windowSecond->setFocusable(true);
3125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3126 setFocusedWindow(windowSecond);
3127
3128 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003129 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3130 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003131
3132 // Focused window should receive event.
3133 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3134 windowTop->assertNoEvents();
3135}
3136
3137TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3138 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3139 sp<FakeWindowHandle> window =
3140 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3141 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3142
3143 window->setFocusable(true);
3144 // Release channel for window is no longer valid.
3145 window->releaseChannel();
3146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3147 setFocusedWindow(window);
3148
3149 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003150 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3151 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003152
3153 // window channel is invalid, so it should not receive any input event.
3154 window->assertNoEvents();
3155}
3156
3157TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3158 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3159 sp<FakeWindowHandle> window =
3160 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3161 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3162
3163 // Window is not focusable.
3164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3165 setFocusedWindow(window);
3166
3167 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003168 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3169 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003170
3171 // window is invalid, so it should not receive any input event.
3172 window->assertNoEvents();
3173}
3174
3175TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3176 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3177 sp<FakeWindowHandle> windowTop =
3178 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3179 sp<FakeWindowHandle> windowSecond =
3180 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3181 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3182
3183 windowTop->setFocusable(true);
3184 windowSecond->setFocusable(true);
3185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3186 setFocusedWindow(windowTop);
3187 windowTop->consumeFocusEvent(true);
3188
3189 setFocusedWindow(windowSecond, windowTop);
3190 windowSecond->consumeFocusEvent(true);
3191 windowTop->consumeFocusEvent(false);
3192
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3194 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003195
3196 // Focused window should receive event.
3197 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3198}
3199
3200TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3201 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3202 sp<FakeWindowHandle> windowTop =
3203 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3204 sp<FakeWindowHandle> windowSecond =
3205 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3206 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3207
3208 windowTop->setFocusable(true);
3209 windowSecond->setFocusable(true);
3210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3211 setFocusedWindow(windowSecond, windowTop);
3212
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003213 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3214 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003215
3216 // Event should be dropped.
3217 windowTop->assertNoEvents();
3218 windowSecond->assertNoEvents();
3219}
3220
3221TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3222 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3223 sp<FakeWindowHandle> window =
3224 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3225 sp<FakeWindowHandle> previousFocusedWindow =
3226 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3227 ADISPLAY_ID_DEFAULT);
3228 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3229
3230 window->setFocusable(true);
3231 previousFocusedWindow->setFocusable(true);
3232 window->setVisible(false);
3233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3234 setFocusedWindow(previousFocusedWindow);
3235 previousFocusedWindow->consumeFocusEvent(true);
3236
3237 // Requesting focus on invisible window takes focus from currently focused window.
3238 setFocusedWindow(window);
3239 previousFocusedWindow->consumeFocusEvent(false);
3240
3241 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003243 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003244 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003245
3246 // Window does not get focus event or key down.
3247 window->assertNoEvents();
3248
3249 // Window becomes visible.
3250 window->setVisible(true);
3251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3252
3253 // Window receives focus event.
3254 window->consumeFocusEvent(true);
3255 // Focused window receives key down.
3256 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3257}
3258
Vishnu Nair599f1412021-06-21 10:39:58 -07003259TEST_F(InputDispatcherTest, DisplayRemoved) {
3260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3261 sp<FakeWindowHandle> window =
3262 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3263 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3264
3265 // window is granted focus.
3266 window->setFocusable(true);
3267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3268 setFocusedWindow(window);
3269 window->consumeFocusEvent(true);
3270
3271 // When a display is removed window loses focus.
3272 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3273 window->consumeFocusEvent(false);
3274}
3275
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003276/**
3277 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3278 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3279 * of the 'slipperyEnterWindow'.
3280 *
3281 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3282 * a way so that the touched location is no longer covered by the top window.
3283 *
3284 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3285 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3286 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3287 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3288 * with ACTION_DOWN).
3289 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3290 * window moved itself away from the touched location and had Flag::SLIPPERY.
3291 *
3292 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3293 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3294 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3295 *
3296 * In this test, we ensure that the event received by the bottom window has
3297 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3298 */
3299TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3300 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3301 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3302
3303 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3304 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3305
3306 sp<FakeWindowHandle> slipperyExitWindow =
3307 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003308 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003309 // Make sure this one overlaps the bottom window
3310 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3311 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3312 // one. Windows with the same owner are not considered to be occluding each other.
3313 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3314
3315 sp<FakeWindowHandle> slipperyEnterWindow =
3316 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3317 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3318
3319 mDispatcher->setInputWindows(
3320 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3321
3322 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3323 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3324 ADISPLAY_ID_DEFAULT, {{50, 50}});
3325 mDispatcher->notifyMotion(&args);
3326 slipperyExitWindow->consumeMotionDown();
3327 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3328 mDispatcher->setInputWindows(
3329 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3330
3331 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3332 ADISPLAY_ID_DEFAULT, {{51, 51}});
3333 mDispatcher->notifyMotion(&args);
3334
3335 slipperyExitWindow->consumeMotionCancel();
3336
3337 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3338 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3339}
3340
Garfield Tan1c7bc862020-01-28 13:24:04 -08003341class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3342protected:
3343 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3344 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3345
Chris Yea209fde2020-07-22 13:54:51 -07003346 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003347 sp<FakeWindowHandle> mWindow;
3348
3349 virtual void SetUp() override {
3350 mFakePolicy = new FakeInputDispatcherPolicy();
3351 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003352 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003353 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3354 ASSERT_EQ(OK, mDispatcher->start());
3355
3356 setUpWindow();
3357 }
3358
3359 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003360 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003361 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3362
Vishnu Nair47074b82020-08-14 11:54:47 -07003363 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003365 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003366 mWindow->consumeFocusEvent(true);
3367 }
3368
Chris Ye2ad95392020-09-01 13:44:44 -07003369 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003370 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003371 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003372 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3373 mDispatcher->notifyKey(&keyArgs);
3374
3375 // Window should receive key down event.
3376 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3377 }
3378
3379 void expectKeyRepeatOnce(int32_t repeatCount) {
3380 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3381 InputEvent* repeatEvent = mWindow->consume();
3382 ASSERT_NE(nullptr, repeatEvent);
3383
3384 uint32_t eventType = repeatEvent->getType();
3385 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3386
3387 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3388 uint32_t eventAction = repeatKeyEvent->getAction();
3389 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3390 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3391 }
3392
Chris Ye2ad95392020-09-01 13:44:44 -07003393 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003394 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003395 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003396 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3397 mDispatcher->notifyKey(&keyArgs);
3398
3399 // Window should receive key down event.
3400 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3401 0 /*expectedFlags*/);
3402 }
3403};
3404
3405TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003406 sendAndConsumeKeyDown(1 /* deviceId */);
3407 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3408 expectKeyRepeatOnce(repeatCount);
3409 }
3410}
3411
3412TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3413 sendAndConsumeKeyDown(1 /* deviceId */);
3414 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3415 expectKeyRepeatOnce(repeatCount);
3416 }
3417 sendAndConsumeKeyDown(2 /* deviceId */);
3418 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003419 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3420 expectKeyRepeatOnce(repeatCount);
3421 }
3422}
3423
3424TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003425 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003426 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003427 sendAndConsumeKeyUp(1 /* deviceId */);
3428 mWindow->assertNoEvents();
3429}
3430
3431TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3432 sendAndConsumeKeyDown(1 /* deviceId */);
3433 expectKeyRepeatOnce(1 /*repeatCount*/);
3434 sendAndConsumeKeyDown(2 /* deviceId */);
3435 expectKeyRepeatOnce(1 /*repeatCount*/);
3436 // Stale key up from device 1.
3437 sendAndConsumeKeyUp(1 /* deviceId */);
3438 // Device 2 is still down, keep repeating
3439 expectKeyRepeatOnce(2 /*repeatCount*/);
3440 expectKeyRepeatOnce(3 /*repeatCount*/);
3441 // Device 2 key up
3442 sendAndConsumeKeyUp(2 /* deviceId */);
3443 mWindow->assertNoEvents();
3444}
3445
3446TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3447 sendAndConsumeKeyDown(1 /* deviceId */);
3448 expectKeyRepeatOnce(1 /*repeatCount*/);
3449 sendAndConsumeKeyDown(2 /* deviceId */);
3450 expectKeyRepeatOnce(1 /*repeatCount*/);
3451 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3452 sendAndConsumeKeyUp(2 /* deviceId */);
3453 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003454 mWindow->assertNoEvents();
3455}
3456
liushenxiang42232912021-05-21 20:24:09 +08003457TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3458 sendAndConsumeKeyDown(DEVICE_ID);
3459 expectKeyRepeatOnce(1 /*repeatCount*/);
3460 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3461 mDispatcher->notifyDeviceReset(&args);
3462 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3463 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3464 mWindow->assertNoEvents();
3465}
3466
Garfield Tan1c7bc862020-01-28 13:24:04 -08003467TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003468 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003469 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3470 InputEvent* repeatEvent = mWindow->consume();
3471 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3472 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3473 IdGenerator::getSource(repeatEvent->getId()));
3474 }
3475}
3476
3477TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003478 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003479
3480 std::unordered_set<int32_t> idSet;
3481 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3482 InputEvent* repeatEvent = mWindow->consume();
3483 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3484 int32_t id = repeatEvent->getId();
3485 EXPECT_EQ(idSet.end(), idSet.find(id));
3486 idSet.insert(id);
3487 }
3488}
3489
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003490/* Test InputDispatcher for MultiDisplay */
3491class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3492public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003493 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003494 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003495
Chris Yea209fde2020-07-22 13:54:51 -07003496 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003497 windowInPrimary =
3498 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003499
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003500 // Set focus window for primary display, but focused display would be second one.
3501 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003502 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003504 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003505 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003506
Chris Yea209fde2020-07-22 13:54:51 -07003507 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003508 windowInSecondary =
3509 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003510 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003511 // Set focus display to second one.
3512 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3513 // Set focus window for second display.
3514 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003515 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003516 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003517 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003518 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003519 }
3520
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003521 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003522 InputDispatcherTest::TearDown();
3523
Chris Yea209fde2020-07-22 13:54:51 -07003524 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003525 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003526 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003527 windowInSecondary.clear();
3528 }
3529
3530protected:
Chris Yea209fde2020-07-22 13:54:51 -07003531 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003532 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003533 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003534 sp<FakeWindowHandle> windowInSecondary;
3535};
3536
3537TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3538 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3540 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003542 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003543 windowInSecondary->assertNoEvents();
3544
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003545 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3548 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003549 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003550 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003551}
3552
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003553TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003554 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003555 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3556 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003557 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003558 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003559 windowInSecondary->assertNoEvents();
3560
3561 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003563 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003565 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003566
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003567 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003568 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003569
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003570 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003571 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3572 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003573
3574 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003575 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003576 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003578 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003579 windowInSecondary->assertNoEvents();
3580}
3581
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582// Test per-display input monitors for motion event.
3583TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003584 FakeMonitorReceiver monitorInPrimary =
3585 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3586 FakeMonitorReceiver monitorInSecondary =
3587 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588
3589 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3591 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003593 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003594 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003596 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597
3598 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3600 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3601 << "Inject motion 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->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003605 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003606
3607 // Test inject a non-pointer motion event.
3608 // If specific a display, it will dispatch to the focused window of particular display,
3609 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003613 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003614 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003615 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003616 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003617}
3618
3619// Test per-display input monitors for key event.
3620TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003621 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003622 FakeMonitorReceiver monitorInPrimary =
3623 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3624 FakeMonitorReceiver monitorInSecondary =
3625 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003626
3627 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3629 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003630 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003631 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003632 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003633 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634}
3635
Vishnu Nair958da932020-08-21 17:12:37 -07003636TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3637 sp<FakeWindowHandle> secondWindowInPrimary =
3638 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3639 secondWindowInPrimary->setFocusable(true);
3640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3641 setFocusedWindow(secondWindowInPrimary);
3642 windowInPrimary->consumeFocusEvent(false);
3643 secondWindowInPrimary->consumeFocusEvent(true);
3644
3645 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3647 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003648 windowInPrimary->assertNoEvents();
3649 windowInSecondary->assertNoEvents();
3650 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3651}
3652
Jackal Guof9696682018-10-05 12:23:23 +08003653class InputFilterTest : public InputDispatcherTest {
3654protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003655 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3656 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003657 NotifyMotionArgs motionArgs;
3658
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003659 motionArgs =
3660 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003661 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003662 motionArgs =
3663 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003664 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003665 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003666 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003667 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3668 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003669 } else {
3670 mFakePolicy->assertFilterInputEventWasNotCalled();
3671 }
3672 }
3673
3674 void testNotifyKey(bool expectToBeFiltered) {
3675 NotifyKeyArgs keyArgs;
3676
3677 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3678 mDispatcher->notifyKey(&keyArgs);
3679 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3680 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003681 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003682
3683 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003684 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003685 } else {
3686 mFakePolicy->assertFilterInputEventWasNotCalled();
3687 }
3688 }
3689};
3690
3691// Test InputFilter for MotionEvent
3692TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3693 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3694 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3695 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3696
3697 // Enable InputFilter
3698 mDispatcher->setInputFilterEnabled(true);
3699 // Test touch on both primary and second display, and check if both events are filtered.
3700 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3701 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3702
3703 // Disable InputFilter
3704 mDispatcher->setInputFilterEnabled(false);
3705 // Test touch on both primary and second display, and check if both events aren't filtered.
3706 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3707 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3708}
3709
3710// Test InputFilter for KeyEvent
3711TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3712 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3713 testNotifyKey(/*expectToBeFiltered*/ false);
3714
3715 // Enable InputFilter
3716 mDispatcher->setInputFilterEnabled(true);
3717 // Send a key event, and check if it is filtered.
3718 testNotifyKey(/*expectToBeFiltered*/ true);
3719
3720 // Disable InputFilter
3721 mDispatcher->setInputFilterEnabled(false);
3722 // Send a key event, and check if it isn't filtered.
3723 testNotifyKey(/*expectToBeFiltered*/ false);
3724}
3725
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003726// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3727// logical display coordinate space.
3728TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3729 ui::Transform firstDisplayTransform;
3730 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3731 ui::Transform secondDisplayTransform;
3732 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3733
3734 std::vector<gui::DisplayInfo> displayInfos(2);
3735 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3736 displayInfos[0].transform = firstDisplayTransform;
3737 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3738 displayInfos[1].transform = secondDisplayTransform;
3739
3740 mDispatcher->onWindowInfosChanged({}, displayInfos);
3741
3742 // Enable InputFilter
3743 mDispatcher->setInputFilterEnabled(true);
3744
3745 // Ensure the correct transforms are used for the displays.
3746 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3747 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3748}
3749
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003750class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3751protected:
3752 virtual void SetUp() override {
3753 InputDispatcherTest::SetUp();
3754
3755 /**
3756 * We don't need to enable input filter to test the injected event policy, but we enabled it
3757 * here to make the tests more realistic, since this policy only matters when inputfilter is
3758 * on.
3759 */
3760 mDispatcher->setInputFilterEnabled(true);
3761
3762 std::shared_ptr<InputApplicationHandle> application =
3763 std::make_shared<FakeApplicationHandle>();
3764 mWindow =
3765 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3766
3767 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3768 mWindow->setFocusable(true);
3769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3770 setFocusedWindow(mWindow);
3771 mWindow->consumeFocusEvent(true);
3772 }
3773
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003774 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3775 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003776 KeyEvent event;
3777
3778 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3779 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3780 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3781 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3782 const int32_t additionalPolicyFlags =
3783 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3785 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3786 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3787 policyFlags | additionalPolicyFlags));
3788
3789 InputEvent* received = mWindow->consume();
3790 ASSERT_NE(nullptr, received);
3791 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003792 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3793 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3794 ASSERT_EQ(flags, keyEvent.getFlags());
3795 }
3796
3797 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3798 int32_t flags) {
3799 MotionEvent event;
3800 PointerProperties pointerProperties[1];
3801 PointerCoords pointerCoords[1];
3802 pointerProperties[0].clear();
3803 pointerProperties[0].id = 0;
3804 pointerCoords[0].clear();
3805 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3806 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3807
3808 ui::Transform identityTransform;
3809 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3810 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3811 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3812 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3813 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003814 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003815 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003816 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3817
3818 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3820 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3821 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3822 policyFlags | additionalPolicyFlags));
3823
3824 InputEvent* received = mWindow->consume();
3825 ASSERT_NE(nullptr, received);
3826 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3827 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3828 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3829 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003830 }
3831
3832private:
3833 sp<FakeWindowHandle> mWindow;
3834};
3835
3836TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003837 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3838 // filter. Without it, the event will no different from a regularly injected event, and the
3839 // injected device id will be overwritten.
3840 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3841 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003842}
3843
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003844TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003845 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003846 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3847 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3848}
3849
3850TEST_F(InputFilterInjectionPolicyTest,
3851 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3852 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3853 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3854 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003855}
3856
3857TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3858 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003859 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003860}
3861
chaviwfd6d3512019-03-25 13:23:49 -07003862class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003863 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003864 InputDispatcherTest::SetUp();
3865
Chris Yea209fde2020-07-22 13:54:51 -07003866 std::shared_ptr<FakeApplicationHandle> application =
3867 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003868 mUnfocusedWindow =
3869 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003870 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3871 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3872 // window.
chaviw3277faf2021-05-19 16:45:23 -05003873 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003874
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003875 mFocusedWindow =
3876 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3877 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003878 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003879
3880 // Set focused application.
3881 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003882 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003883
3884 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003886 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003887 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003888 }
3889
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003890 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003891 InputDispatcherTest::TearDown();
3892
3893 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003894 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003895 }
3896
3897protected:
3898 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003899 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003900 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003901};
3902
3903// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3904// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3905// the onPointerDownOutsideFocus callback.
3906TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003908 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3909 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003910 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003911 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003912
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003913 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003914 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3915}
3916
3917// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3918// DOWN on the window that doesn't have focus. Ensure no window received the
3919// onPointerDownOutsideFocus callback.
3920TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003921 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003922 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003923 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003924 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003925
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003926 ASSERT_TRUE(mDispatcher->waitForIdle());
3927 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003928}
3929
3930// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3931// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3932TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3934 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003935 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003936 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003937
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003938 ASSERT_TRUE(mDispatcher->waitForIdle());
3939 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003940}
3941
3942// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3943// DOWN on the window that already has focus. Ensure no window received the
3944// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003945TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003948 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003950 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003951
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003952 ASSERT_TRUE(mDispatcher->waitForIdle());
3953 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003954}
3955
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003956// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3957// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3958TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3959 const MotionEvent event =
3960 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3961 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3962 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3963 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3964 .build();
3965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3967 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3968
3969 ASSERT_TRUE(mDispatcher->waitForIdle());
3970 mFakePolicy->assertOnPointerDownWasNotCalled();
3971 // Ensure that the unfocused window did not receive any FOCUS events.
3972 mUnfocusedWindow->assertNoEvents();
3973}
3974
chaviwaf87b3e2019-10-01 16:59:28 -07003975// These tests ensures we can send touch events to a single client when there are multiple input
3976// windows that point to the same client token.
3977class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3978 virtual void SetUp() override {
3979 InputDispatcherTest::SetUp();
3980
Chris Yea209fde2020-07-22 13:54:51 -07003981 std::shared_ptr<FakeApplicationHandle> application =
3982 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003983 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3984 ADISPLAY_ID_DEFAULT);
3985 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3986 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003987 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003988 mWindow1->setFrame(Rect(0, 0, 100, 100));
3989
3990 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3991 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003992 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003993 mWindow2->setFrame(Rect(100, 100, 200, 200));
3994
Arthur Hung72d8dc32020-03-28 00:48:39 +00003995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003996 }
3997
3998protected:
3999 sp<FakeWindowHandle> mWindow1;
4000 sp<FakeWindowHandle> mWindow2;
4001
4002 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004003 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004004 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4005 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004006 }
4007
4008 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4009 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004010 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004011 InputEvent* event = window->consume();
4012
4013 ASSERT_NE(nullptr, event) << name.c_str()
4014 << ": consumer should have returned non-NULL event.";
4015
4016 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4017 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4018 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4019
4020 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004021 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004022
4023 for (size_t i = 0; i < points.size(); i++) {
4024 float expectedX = points[i].x;
4025 float expectedY = points[i].y;
4026
4027 EXPECT_EQ(expectedX, motionEvent.getX(i))
4028 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4029 << ", got " << motionEvent.getX(i);
4030 EXPECT_EQ(expectedY, motionEvent.getY(i))
4031 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4032 << ", got " << motionEvent.getY(i);
4033 }
4034 }
chaviw9eaa22c2020-07-01 16:21:27 -07004035
4036 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4037 std::vector<PointF> expectedPoints) {
4038 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4039 ADISPLAY_ID_DEFAULT, touchedPoints);
4040 mDispatcher->notifyMotion(&motionArgs);
4041
4042 // Always consume from window1 since it's the window that has the InputReceiver
4043 consumeMotionEvent(mWindow1, action, expectedPoints);
4044 }
chaviwaf87b3e2019-10-01 16:59:28 -07004045};
4046
4047TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4048 // Touch Window 1
4049 PointF touchedPoint = {10, 10};
4050 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004051 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004052
4053 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004054 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004055
4056 // Touch Window 2
4057 touchedPoint = {150, 150};
4058 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004059 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004060}
4061
chaviw9eaa22c2020-07-01 16:21:27 -07004062TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4063 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004064 mWindow2->setWindowScale(0.5f, 0.5f);
4065
4066 // Touch Window 1
4067 PointF touchedPoint = {10, 10};
4068 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004069 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004070 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004071 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004072
4073 // Touch Window 2
4074 touchedPoint = {150, 150};
4075 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004076 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4077 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004078
chaviw9eaa22c2020-07-01 16:21:27 -07004079 // Update the transform so rotation is set
4080 mWindow2->setWindowTransform(0, -1, 1, 0);
4081 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4082 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004083}
4084
chaviw9eaa22c2020-07-01 16:21:27 -07004085TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004086 mWindow2->setWindowScale(0.5f, 0.5f);
4087
4088 // Touch Window 1
4089 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4090 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004091 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004092
4093 // Touch Window 2
4094 int32_t actionPointerDown =
4095 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004096 touchedPoints.push_back(PointF{150, 150});
4097 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4098 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004099
chaviw9eaa22c2020-07-01 16:21:27 -07004100 // Release Window 2
4101 int32_t actionPointerUp =
4102 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4103 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4104 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004105
chaviw9eaa22c2020-07-01 16:21:27 -07004106 // Update the transform so rotation is set for Window 2
4107 mWindow2->setWindowTransform(0, -1, 1, 0);
4108 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4109 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004110}
4111
chaviw9eaa22c2020-07-01 16:21:27 -07004112TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004113 mWindow2->setWindowScale(0.5f, 0.5f);
4114
4115 // Touch Window 1
4116 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4117 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004118 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004119
4120 // Touch Window 2
4121 int32_t actionPointerDown =
4122 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004123 touchedPoints.push_back(PointF{150, 150});
4124 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004125
chaviw9eaa22c2020-07-01 16:21:27 -07004126 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004127
4128 // Move both windows
4129 touchedPoints = {{20, 20}, {175, 175}};
4130 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4131 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4132
chaviw9eaa22c2020-07-01 16:21:27 -07004133 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004134
chaviw9eaa22c2020-07-01 16:21:27 -07004135 // Release Window 2
4136 int32_t actionPointerUp =
4137 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4138 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4139 expectedPoints.pop_back();
4140
4141 // Touch Window 2
4142 mWindow2->setWindowTransform(0, -1, 1, 0);
4143 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4144 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4145
4146 // Move both windows
4147 touchedPoints = {{20, 20}, {175, 175}};
4148 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4149 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4150
4151 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004152}
4153
4154TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4155 mWindow1->setWindowScale(0.5f, 0.5f);
4156
4157 // Touch Window 1
4158 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4159 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004160 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004161
4162 // Touch Window 2
4163 int32_t actionPointerDown =
4164 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004165 touchedPoints.push_back(PointF{150, 150});
4166 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004167
chaviw9eaa22c2020-07-01 16:21:27 -07004168 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004169
4170 // Move both windows
4171 touchedPoints = {{20, 20}, {175, 175}};
4172 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4173 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4174
chaviw9eaa22c2020-07-01 16:21:27 -07004175 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004176}
4177
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004178class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4179 virtual void SetUp() override {
4180 InputDispatcherTest::SetUp();
4181
Chris Yea209fde2020-07-22 13:54:51 -07004182 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004183 mApplication->setDispatchingTimeout(20ms);
4184 mWindow =
4185 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4186 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004187 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004188 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004189 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4190 // window.
chaviw3277faf2021-05-19 16:45:23 -05004191 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004192
4193 // Set focused application.
4194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4195
4196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004197 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004198 mWindow->consumeFocusEvent(true);
4199 }
4200
4201 virtual void TearDown() override {
4202 InputDispatcherTest::TearDown();
4203 mWindow.clear();
4204 }
4205
4206protected:
Chris Yea209fde2020-07-22 13:54:51 -07004207 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004208 sp<FakeWindowHandle> mWindow;
4209 static constexpr PointF WINDOW_LOCATION = {20, 20};
4210
4211 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004212 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004213 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4214 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004216 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4217 WINDOW_LOCATION));
4218 }
4219};
4220
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004221// Send a tap and respond, which should not cause an ANR.
4222TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4223 tapOnWindow();
4224 mWindow->consumeMotionDown();
4225 mWindow->consumeMotionUp();
4226 ASSERT_TRUE(mDispatcher->waitForIdle());
4227 mFakePolicy->assertNotifyAnrWasNotCalled();
4228}
4229
4230// Send a regular key and respond, which should not cause an ANR.
4231TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004233 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4234 ASSERT_TRUE(mDispatcher->waitForIdle());
4235 mFakePolicy->assertNotifyAnrWasNotCalled();
4236}
4237
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004238TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4239 mWindow->setFocusable(false);
4240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4241 mWindow->consumeFocusEvent(false);
4242
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004244 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004245 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4246 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004248 // Key will not go to window because we have no focused window.
4249 // The 'no focused window' ANR timer should start instead.
4250
4251 // Now, the focused application goes away.
4252 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4253 // The key should get dropped and there should be no ANR.
4254
4255 ASSERT_TRUE(mDispatcher->waitForIdle());
4256 mFakePolicy->assertNotifyAnrWasNotCalled();
4257}
4258
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004260// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4261// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004262TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004264 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4265 WINDOW_LOCATION));
4266
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004267 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4268 ASSERT_TRUE(sequenceNum);
4269 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004270 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004271
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004272 mWindow->finishEvent(*sequenceNum);
4273 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4274 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004275 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004276 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004277}
4278
4279// Send a key to the app and have the app not respond right away.
4280TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4281 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004283 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4284 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004285 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004286 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004287 ASSERT_TRUE(mDispatcher->waitForIdle());
4288}
4289
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004290// We have a focused application, but no focused window
4291TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004292 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4294 mWindow->consumeFocusEvent(false);
4295
4296 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4299 WINDOW_LOCATION));
4300 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4301 mDispatcher->waitForIdle();
4302 mFakePolicy->assertNotifyAnrWasNotCalled();
4303
4304 // Once a focused event arrives, we get an ANR for this application
4305 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4306 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004308 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004309 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004311 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004312 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004313 ASSERT_TRUE(mDispatcher->waitForIdle());
4314}
4315
4316// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004317// Make sure that we don't notify policy twice about the same ANR.
4318TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004319 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4321 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004322
4323 // Once a focused event arrives, we get an ANR for this application
4324 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4325 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004327 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004328 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004330 const std::chrono::duration appTimeout =
4331 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004332 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004333
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004334 std::this_thread::sleep_for(appTimeout);
4335 // ANR should not be raised again. It is up to policy to do that if it desires.
4336 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004337
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004338 // If we now get a focused window, the ANR should stop, but the policy handles that via
4339 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004340 ASSERT_TRUE(mDispatcher->waitForIdle());
4341}
4342
4343// We have a focused application, but no focused window
4344TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004345 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4347 mWindow->consumeFocusEvent(false);
4348
4349 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004350 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004351 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004352 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4353 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004354
4355 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004356 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004357
4358 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004360 ASSERT_TRUE(mDispatcher->waitForIdle());
4361 mWindow->assertNoEvents();
4362}
4363
4364/**
4365 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4366 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4367 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4368 * the ANR mechanism should still work.
4369 *
4370 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4371 * DOWN event, while not responding on the second one.
4372 */
4373TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4374 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4375 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4376 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4377 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4378 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004380
4381 // Now send ACTION_UP, with identical timestamp
4382 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4383 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4384 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4385 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387
4388 // We have now sent down and up. Let's consume first event and then ANR on the second.
4389 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4390 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004391 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004392}
4393
4394// If an app is not responding to a key event, gesture monitors should continue to receive
4395// new motion events
4396TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4397 FakeMonitorReceiver monitor =
4398 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4399 true /*isGestureMonitor*/);
4400
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4402 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004403 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004405
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->consumeKeyUp(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 an app is not responding to a motion event, gesture monitors should continue to receive
4423// new motion events
4424TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4425 FakeMonitorReceiver monitor =
4426 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4427 true /*isGestureMonitor*/);
4428
4429 tapOnWindow();
4430 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4431 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4432
4433 mWindow->consumeMotionDown();
4434 // Stuck on the ACTION_UP
4435 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004436 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004437
4438 // New tap will go to the gesture monitor, but not to the window
4439 tapOnWindow();
4440 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4441 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4442
4443 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4444 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004445 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 mWindow->assertNoEvents();
4447 monitor.assertNoEvents();
4448}
4449
4450// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4451// process events, you don't get an anr. When the window later becomes unresponsive again, you
4452// get an ANR again.
4453// 1. tap -> block on ACTION_UP -> receive ANR
4454// 2. consume all pending events (= queue becomes healthy again)
4455// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4456TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4457 tapOnWindow();
4458
4459 mWindow->consumeMotionDown();
4460 // Block on ACTION_UP
4461 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004462 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004463 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4464 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004465 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004466 mWindow->assertNoEvents();
4467
4468 tapOnWindow();
4469 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004470 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471 mWindow->consumeMotionUp();
4472
4473 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004474 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004475 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476 mWindow->assertNoEvents();
4477}
4478
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004479// If a connection remains unresponsive for a while, make sure policy is only notified once about
4480// it.
4481TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4484 WINDOW_LOCATION));
4485
4486 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004487 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004488 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004489 // 'notifyConnectionUnresponsive' should only be called once per connection
4490 mFakePolicy->assertNotifyAnrWasNotCalled();
4491 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492 mWindow->consumeMotionDown();
4493 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4494 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4495 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004496 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004497 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004498 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499}
4500
4501/**
4502 * If a window is processing a motion event, and then a key event comes in, the key event should
4503 * not to to the focused window until the motion is processed.
4504 *
4505 * Warning!!!
4506 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4507 * and the injection timeout that we specify when injecting the key.
4508 * We must have the injection timeout (10ms) be smaller than
4509 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4510 *
4511 * If that value changes, this test should also change.
4512 */
4513TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4514 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4515 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4516
4517 tapOnWindow();
4518 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4519 ASSERT_TRUE(downSequenceNum);
4520 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4521 ASSERT_TRUE(upSequenceNum);
4522 // Don't finish the events yet, and send a key
4523 // Injection will "succeed" because we will eventually give up and send the key to the focused
4524 // window even if motions are still being processed. But because the injection timeout is short,
4525 // we will receive INJECTION_TIMED_OUT as the result.
4526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004527 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004528 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004529 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4530 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004531 // Key will not be sent to the window, yet, because the window is still processing events
4532 // and the key remains pending, waiting for the touch events to be processed
4533 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4534 ASSERT_FALSE(keySequenceNum);
4535
4536 std::this_thread::sleep_for(500ms);
4537 // if we wait long enough though, dispatcher will give up, and still send the key
4538 // to the focused window, even though we have not yet finished the motion event
4539 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4540 mWindow->finishEvent(*downSequenceNum);
4541 mWindow->finishEvent(*upSequenceNum);
4542}
4543
4544/**
4545 * If a window is processing a motion event, and then a key event comes in, the key event should
4546 * not go to the focused window until the motion is processed.
4547 * If then a new motion comes in, then the pending key event should be going to the currently
4548 * focused window right away.
4549 */
4550TEST_F(InputDispatcherSingleWindowAnr,
4551 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4552 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4554
4555 tapOnWindow();
4556 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4557 ASSERT_TRUE(downSequenceNum);
4558 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4559 ASSERT_TRUE(upSequenceNum);
4560 // Don't finish the events yet, and send a key
4561 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004564 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004565 // At this point, key is still pending, and should not be sent to the application yet.
4566 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4567 ASSERT_FALSE(keySequenceNum);
4568
4569 // Now tap down again. It should cause the pending key to go to the focused window right away.
4570 tapOnWindow();
4571 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4572 // the other events yet. We can finish events in any order.
4573 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4574 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4575 mWindow->consumeMotionDown();
4576 mWindow->consumeMotionUp();
4577 mWindow->assertNoEvents();
4578}
4579
4580class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4581 virtual void SetUp() override {
4582 InputDispatcherTest::SetUp();
4583
Chris Yea209fde2020-07-22 13:54:51 -07004584 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585 mApplication->setDispatchingTimeout(10ms);
4586 mUnfocusedWindow =
4587 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4588 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4589 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4590 // window.
4591 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004592 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4593 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4594 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004595
4596 mFocusedWindow =
4597 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004598 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004599 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004600 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004601
4602 // Set focused application.
4603 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004604 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004605
4606 // Expect one focus window exist in display.
4607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004608 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 mFocusedWindow->consumeFocusEvent(true);
4610 }
4611
4612 virtual void TearDown() override {
4613 InputDispatcherTest::TearDown();
4614
4615 mUnfocusedWindow.clear();
4616 mFocusedWindow.clear();
4617 }
4618
4619protected:
Chris Yea209fde2020-07-22 13:54:51 -07004620 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621 sp<FakeWindowHandle> mUnfocusedWindow;
4622 sp<FakeWindowHandle> mFocusedWindow;
4623 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4624 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4625 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4626
4627 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4628
4629 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4630
4631private:
4632 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004634 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4635 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4638 location));
4639 }
4640};
4641
4642// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4643// should be ANR'd first.
4644TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004645 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004646 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4647 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649 mFocusedWindow->consumeMotionDown();
4650 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4651 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4652 // We consumed all events, so no ANR
4653 ASSERT_TRUE(mDispatcher->waitForIdle());
4654 mFakePolicy->assertNotifyAnrWasNotCalled();
4655
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004656 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4658 FOCUSED_WINDOW_LOCATION));
4659 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4660 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661
4662 const std::chrono::duration timeout =
4663 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004664 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004665 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4666 // sequence to make it consistent
4667 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004669 mFocusedWindow->consumeMotionDown();
4670 // This cancel is generated because the connection was unresponsive
4671 mFocusedWindow->consumeMotionCancel();
4672 mFocusedWindow->assertNoEvents();
4673 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004675 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004676 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677}
4678
4679// If we have 2 windows with identical timeouts that are both unresponsive,
4680// it doesn't matter which order they should have ANR.
4681// But we should receive ANR for both.
4682TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4683 // Set the timeout for unfocused window to match the focused window
4684 mUnfocusedWindow->setDispatchingTimeout(10ms);
4685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4686
4687 tapOnFocusedWindow();
4688 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004689 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4690 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004691
4692 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004693 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4694 mFocusedWindow->getToken() == anrConnectionToken2);
4695 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4696 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697
4698 ASSERT_TRUE(mDispatcher->waitForIdle());
4699 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004700
4701 mFocusedWindow->consumeMotionDown();
4702 mFocusedWindow->consumeMotionUp();
4703 mUnfocusedWindow->consumeMotionOutside();
4704
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004705 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4706 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004707
4708 // Both applications should be marked as responsive, in any order
4709 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4710 mFocusedWindow->getToken() == responsiveToken2);
4711 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4712 mUnfocusedWindow->getToken() == responsiveToken2);
4713 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714}
4715
4716// If a window is already not responding, the second tap on the same window should be ignored.
4717// We should also log an error to account for the dropped event (not tested here).
4718// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4719TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4720 tapOnFocusedWindow();
4721 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4722 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4723 // Receive the events, but don't respond
4724 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4725 ASSERT_TRUE(downEventSequenceNum);
4726 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4727 ASSERT_TRUE(upEventSequenceNum);
4728 const std::chrono::duration timeout =
4729 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004730 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731
4732 // Tap once again
4733 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004734 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4736 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4739 FOCUSED_WINDOW_LOCATION));
4740 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4741 // valid touch target
4742 mUnfocusedWindow->assertNoEvents();
4743
4744 // Consume the first tap
4745 mFocusedWindow->finishEvent(*downEventSequenceNum);
4746 mFocusedWindow->finishEvent(*upEventSequenceNum);
4747 ASSERT_TRUE(mDispatcher->waitForIdle());
4748 // The second tap did not go to the focused window
4749 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004750 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004751 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752 mFakePolicy->assertNotifyAnrWasNotCalled();
4753}
4754
4755// If you tap outside of all windows, there will not be ANR
4756TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004757 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4759 LOCATION_OUTSIDE_ALL_WINDOWS));
4760 ASSERT_TRUE(mDispatcher->waitForIdle());
4761 mFakePolicy->assertNotifyAnrWasNotCalled();
4762}
4763
4764// Since the focused window is paused, tapping on it should not produce any events
4765TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4766 mFocusedWindow->setPaused(true);
4767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4768
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4771 FOCUSED_WINDOW_LOCATION));
4772
4773 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4774 ASSERT_TRUE(mDispatcher->waitForIdle());
4775 // Should not ANR because the window is paused, and touches shouldn't go to it
4776 mFakePolicy->assertNotifyAnrWasNotCalled();
4777
4778 mFocusedWindow->assertNoEvents();
4779 mUnfocusedWindow->assertNoEvents();
4780}
4781
4782/**
4783 * If a window is processing a motion event, and then a key event comes in, the key event should
4784 * not to to the focused window until the motion is processed.
4785 * If a different window becomes focused at this time, the key should go to that window instead.
4786 *
4787 * Warning!!!
4788 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4789 * and the injection timeout that we specify when injecting the key.
4790 * We must have the injection timeout (10ms) be smaller than
4791 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4792 *
4793 * If that value changes, this test should also change.
4794 */
4795TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4796 // Set a long ANR timeout to prevent it from triggering
4797 mFocusedWindow->setDispatchingTimeout(2s);
4798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4799
4800 tapOnUnfocusedWindow();
4801 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4802 ASSERT_TRUE(downSequenceNum);
4803 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4804 ASSERT_TRUE(upSequenceNum);
4805 // Don't finish the events yet, and send a key
4806 // Injection will succeed because we will eventually give up and send the key to the focused
4807 // window even if motions are still being processed.
4808
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 // Key will not be sent to the window, yet, because the window is still processing events
4814 // and the key remains pending, waiting for the touch events to be processed
4815 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4816 ASSERT_FALSE(keySequenceNum);
4817
4818 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004819 mFocusedWindow->setFocusable(false);
4820 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004822 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823
4824 // Focus events should precede the key events
4825 mUnfocusedWindow->consumeFocusEvent(true);
4826 mFocusedWindow->consumeFocusEvent(false);
4827
4828 // Finish the tap events, which should unblock dispatcher
4829 mUnfocusedWindow->finishEvent(*downSequenceNum);
4830 mUnfocusedWindow->finishEvent(*upSequenceNum);
4831
4832 // Now that all queues are cleared and no backlog in the connections, the key event
4833 // can finally go to the newly focused "mUnfocusedWindow".
4834 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4835 mFocusedWindow->assertNoEvents();
4836 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004837 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838}
4839
4840// When the touch stream is split across 2 windows, and one of them does not respond,
4841// then ANR should be raised and the touch should be canceled for the unresponsive window.
4842// The other window should not be affected by that.
4843TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4844 // Touch Window 1
4845 NotifyMotionArgs motionArgs =
4846 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4847 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4848 mDispatcher->notifyMotion(&motionArgs);
4849 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4850 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4851
4852 // Touch Window 2
4853 int32_t actionPointerDown =
4854 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4855
4856 motionArgs =
4857 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4858 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4859 mDispatcher->notifyMotion(&motionArgs);
4860
4861 const std::chrono::duration timeout =
4862 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004863 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864
4865 mUnfocusedWindow->consumeMotionDown();
4866 mFocusedWindow->consumeMotionDown();
4867 // Focused window may or may not receive ACTION_MOVE
4868 // But it should definitely receive ACTION_CANCEL due to the ANR
4869 InputEvent* event;
4870 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4871 ASSERT_TRUE(moveOrCancelSequenceNum);
4872 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4873 ASSERT_NE(nullptr, event);
4874 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4875 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4876 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4877 mFocusedWindow->consumeMotionCancel();
4878 } else {
4879 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4880 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004882 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004883
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 mUnfocusedWindow->assertNoEvents();
4885 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004886 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887}
4888
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004889/**
4890 * If we have no focused window, and a key comes in, we start the ANR timer.
4891 * The focused application should add a focused window before the timer runs out to prevent ANR.
4892 *
4893 * If the user touches another application during this time, the key should be dropped.
4894 * Next, if a new focused window comes in, without toggling the focused application,
4895 * then no ANR should occur.
4896 *
4897 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4898 * but in some cases the policy may not update the focused application.
4899 */
4900TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4901 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4902 std::make_shared<FakeApplicationHandle>();
4903 focusedApplication->setDispatchingTimeout(60ms);
4904 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4905 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4906 mFocusedWindow->setFocusable(false);
4907
4908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4909 mFocusedWindow->consumeFocusEvent(false);
4910
4911 // Send a key. The ANR timer should start because there is no focused window.
4912 // 'focusedApplication' will get blamed if this timer completes.
4913 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004914 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004915 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004916 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4917 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004919
4920 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4921 // then the injected touches won't cause the focused event to get dropped.
4922 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4923 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4924 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4925 // For this test, it means that the key would get delivered to the window once it becomes
4926 // focused.
4927 std::this_thread::sleep_for(10ms);
4928
4929 // Touch unfocused window. This should force the pending key to get dropped.
4930 NotifyMotionArgs motionArgs =
4931 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4932 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4933 mDispatcher->notifyMotion(&motionArgs);
4934
4935 // We do not consume the motion right away, because that would require dispatcher to first
4936 // process (== drop) the key event, and by that time, ANR will be raised.
4937 // Set the focused window first.
4938 mFocusedWindow->setFocusable(true);
4939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4940 setFocusedWindow(mFocusedWindow);
4941 mFocusedWindow->consumeFocusEvent(true);
4942 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4943 // to another application. This could be a bug / behaviour in the policy.
4944
4945 mUnfocusedWindow->consumeMotionDown();
4946
4947 ASSERT_TRUE(mDispatcher->waitForIdle());
4948 // Should not ANR because we actually have a focused window. It was just added too slowly.
4949 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4950}
4951
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004952// These tests ensure we cannot send touch events to a window that's positioned behind a window
4953// that has feature NO_INPUT_CHANNEL.
4954// Layout:
4955// Top (closest to user)
4956// mNoInputWindow (above all windows)
4957// mBottomWindow
4958// Bottom (furthest from user)
4959class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4960 virtual void SetUp() override {
4961 InputDispatcherTest::SetUp();
4962
4963 mApplication = std::make_shared<FakeApplicationHandle>();
4964 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4965 "Window without input channel", ADISPLAY_ID_DEFAULT,
4966 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4967
chaviw3277faf2021-05-19 16:45:23 -05004968 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004969 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4970 // It's perfectly valid for this window to not have an associated input channel
4971
4972 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4973 ADISPLAY_ID_DEFAULT);
4974 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4975
4976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4977 }
4978
4979protected:
4980 std::shared_ptr<FakeApplicationHandle> mApplication;
4981 sp<FakeWindowHandle> mNoInputWindow;
4982 sp<FakeWindowHandle> mBottomWindow;
4983};
4984
4985TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
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 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4995 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4996 // and therefore should prevent mBottomWindow from receiving touches
4997 mBottomWindow->assertNoEvents();
4998}
4999
5000/**
5001 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5002 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5003 */
5004TEST_F(InputDispatcherMultiWindowOcclusionTests,
5005 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5006 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5007 "Window with input channel and NO_INPUT_CHANNEL",
5008 ADISPLAY_ID_DEFAULT);
5009
chaviw3277faf2021-05-19 16:45:23 -05005010 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005011 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5013
5014 PointF touchedPoint = {10, 10};
5015
5016 NotifyMotionArgs motionArgs =
5017 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5018 ADISPLAY_ID_DEFAULT, {touchedPoint});
5019 mDispatcher->notifyMotion(&motionArgs);
5020
5021 mNoInputWindow->assertNoEvents();
5022 mBottomWindow->assertNoEvents();
5023}
5024
Vishnu Nair958da932020-08-21 17:12:37 -07005025class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5026protected:
5027 std::shared_ptr<FakeApplicationHandle> mApp;
5028 sp<FakeWindowHandle> mWindow;
5029 sp<FakeWindowHandle> mMirror;
5030
5031 virtual void SetUp() override {
5032 InputDispatcherTest::SetUp();
5033 mApp = std::make_shared<FakeApplicationHandle>();
5034 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5035 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5036 mWindow->getToken());
5037 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5038 mWindow->setFocusable(true);
5039 mMirror->setFocusable(true);
5040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5041 }
5042};
5043
5044TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5045 // Request focus on a mirrored window
5046 setFocusedWindow(mMirror);
5047
5048 // window gets focused
5049 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5051 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005052 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5053}
5054
5055// A focused & mirrored window remains focused only if the window and its mirror are both
5056// focusable.
5057TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5058 setFocusedWindow(mMirror);
5059
5060 // window gets focused
5061 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5063 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005064 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5066 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005067 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5068
5069 mMirror->setFocusable(false);
5070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5071
5072 // window loses focus since one of the windows associated with the token in not focusable
5073 mWindow->consumeFocusEvent(false);
5074
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005075 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5076 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005077 mWindow->assertNoEvents();
5078}
5079
5080// A focused & mirrored window remains focused until the window and its mirror both become
5081// invisible.
5082TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5083 setFocusedWindow(mMirror);
5084
5085 // window gets focused
5086 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5088 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005089 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5091 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005092 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5093
5094 mMirror->setVisible(false);
5095 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5096
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5098 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005099 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5101 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005102 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5103
5104 mWindow->setVisible(false);
5105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5106
5107 // window loses focus only after all windows associated with the token become invisible.
5108 mWindow->consumeFocusEvent(false);
5109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005110 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5111 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005112 mWindow->assertNoEvents();
5113}
5114
5115// A focused & mirrored window remains focused until both windows are removed.
5116TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5117 setFocusedWindow(mMirror);
5118
5119 // window gets focused
5120 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5122 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005123 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005124 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5125 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005126 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5127
5128 // single window is removed but the window token remains focused
5129 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5130
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5132 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005133 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5135 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005136 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5137
5138 // Both windows are removed
5139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5140 mWindow->consumeFocusEvent(false);
5141
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005142 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5143 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005144 mWindow->assertNoEvents();
5145}
5146
5147// Focus request can be pending until one window becomes visible.
5148TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5149 // Request focus on an invisible mirror.
5150 mWindow->setVisible(false);
5151 mMirror->setVisible(false);
5152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5153 setFocusedWindow(mMirror);
5154
5155 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005157 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005158 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005159
5160 mMirror->setVisible(true);
5161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5162
5163 // window gets focused
5164 mWindow->consumeFocusEvent(true);
5165 // window gets the pending key event
5166 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5167}
Prabir Pradhan99987712020-11-10 18:43:05 -08005168
5169class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5170protected:
5171 std::shared_ptr<FakeApplicationHandle> mApp;
5172 sp<FakeWindowHandle> mWindow;
5173 sp<FakeWindowHandle> mSecondWindow;
5174
5175 void SetUp() override {
5176 InputDispatcherTest::SetUp();
5177 mApp = std::make_shared<FakeApplicationHandle>();
5178 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5179 mWindow->setFocusable(true);
5180 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5181 mSecondWindow->setFocusable(true);
5182
5183 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5185
5186 setFocusedWindow(mWindow);
5187 mWindow->consumeFocusEvent(true);
5188 }
5189
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005190 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5191 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005192 mDispatcher->notifyPointerCaptureChanged(&args);
5193 }
5194
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005195 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5196 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005197 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005198 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5199 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005200 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005201 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005202 }
5203};
5204
5205TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5206 // Ensure that capture cannot be obtained for unfocused windows.
5207 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5208 mFakePolicy->assertSetPointerCaptureNotCalled();
5209 mSecondWindow->assertNoEvents();
5210
5211 // Ensure that capture can be enabled from the focus window.
5212 requestAndVerifyPointerCapture(mWindow, true);
5213
5214 // Ensure that capture cannot be disabled from a window that does not have capture.
5215 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5216 mFakePolicy->assertSetPointerCaptureNotCalled();
5217
5218 // Ensure that capture can be disabled from the window with capture.
5219 requestAndVerifyPointerCapture(mWindow, false);
5220}
5221
5222TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005223 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005224
5225 setFocusedWindow(mSecondWindow);
5226
5227 // Ensure that the capture disabled event was sent first.
5228 mWindow->consumeCaptureEvent(false);
5229 mWindow->consumeFocusEvent(false);
5230 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005231 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005232
5233 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005234 notifyPointerCaptureChanged({});
5235 notifyPointerCaptureChanged(request);
5236 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005237 mWindow->assertNoEvents();
5238 mSecondWindow->assertNoEvents();
5239 mFakePolicy->assertSetPointerCaptureNotCalled();
5240}
5241
5242TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005243 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005244
5245 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005246 notifyPointerCaptureChanged({});
5247 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005248
5249 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005250 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005251 mWindow->consumeCaptureEvent(false);
5252 mWindow->assertNoEvents();
5253}
5254
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005255TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5256 requestAndVerifyPointerCapture(mWindow, true);
5257
5258 // The first window loses focus.
5259 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005260 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005261 mWindow->consumeCaptureEvent(false);
5262
5263 // Request Pointer Capture from the second window before the notification from InputReader
5264 // arrives.
5265 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005266 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005267
5268 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005269 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005270
5271 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005272 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005273
5274 mSecondWindow->consumeFocusEvent(true);
5275 mSecondWindow->consumeCaptureEvent(true);
5276}
5277
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005278TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5279 // App repeatedly enables and disables capture.
5280 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5281 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5282 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5283 mFakePolicy->assertSetPointerCaptureCalled(false);
5284 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5285 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5286
5287 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5288 // first request is now stale, this should do nothing.
5289 notifyPointerCaptureChanged(firstRequest);
5290 mWindow->assertNoEvents();
5291
5292 // InputReader notifies that the second request was enabled.
5293 notifyPointerCaptureChanged(secondRequest);
5294 mWindow->consumeCaptureEvent(true);
5295}
5296
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005297class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5298protected:
5299 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005300
5301 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5302 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5303
5304 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5305 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5306
5307 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5308 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5309 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5310 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5311 MAXIMUM_OBSCURING_OPACITY);
5312
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005313 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005314 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005315 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005316
5317 sp<FakeWindowHandle> mTouchWindow;
5318
5319 virtual void SetUp() override {
5320 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005321 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005322 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5323 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5324 }
5325
5326 virtual void TearDown() override {
5327 InputDispatcherTest::TearDown();
5328 mTouchWindow.clear();
5329 }
5330
chaviw3277faf2021-05-19 16:45:23 -05005331 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5332 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005333 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005334 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005335 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005336 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005337 return window;
5338 }
5339
5340 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5341 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5342 sp<FakeWindowHandle> window =
5343 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5344 // Generate an arbitrary PID based on the UID
5345 window->setOwnerInfo(1777 + (uid % 10000), uid);
5346 return window;
5347 }
5348
5349 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5350 NotifyMotionArgs args =
5351 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5352 ADISPLAY_ID_DEFAULT, points);
5353 mDispatcher->notifyMotion(&args);
5354 }
5355};
5356
5357TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005358 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005359 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005361
5362 touch();
5363
5364 mTouchWindow->assertNoEvents();
5365}
5366
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005367TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005368 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5369 const sp<FakeWindowHandle>& w =
5370 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5372
5373 touch();
5374
5375 mTouchWindow->assertNoEvents();
5376}
5377
5378TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005379 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5380 const sp<FakeWindowHandle>& w =
5381 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5383
5384 touch();
5385
5386 w->assertNoEvents();
5387}
5388
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005389TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005390 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005392
5393 touch();
5394
5395 mTouchWindow->consumeAnyMotionDown();
5396}
5397
5398TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005399 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005400 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005401 w->setFrame(Rect(0, 0, 50, 50));
5402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005403
5404 touch({PointF{100, 100}});
5405
5406 mTouchWindow->consumeAnyMotionDown();
5407}
5408
5409TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005410 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005411 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5413
5414 touch();
5415
5416 mTouchWindow->consumeAnyMotionDown();
5417}
5418
5419TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5420 const sp<FakeWindowHandle>& w =
5421 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005423
5424 touch();
5425
5426 mTouchWindow->consumeAnyMotionDown();
5427}
5428
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005429TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5430 const sp<FakeWindowHandle>& w =
5431 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5433
5434 touch();
5435
5436 w->assertNoEvents();
5437}
5438
5439/**
5440 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5441 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5442 * window, the occluding window will still receive ACTION_OUTSIDE event.
5443 */
5444TEST_F(InputDispatcherUntrustedTouchesTest,
5445 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5446 const sp<FakeWindowHandle>& w =
5447 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005448 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005449 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5450
5451 touch();
5452
5453 w->consumeMotionOutside();
5454}
5455
5456TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5457 const sp<FakeWindowHandle>& w =
5458 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005459 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5461
5462 touch();
5463
5464 InputEvent* event = w->consume();
5465 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5466 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5467 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5468 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5469}
5470
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005471TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005472 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005473 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5474 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5476
5477 touch();
5478
5479 mTouchWindow->consumeAnyMotionDown();
5480}
5481
5482TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5483 const sp<FakeWindowHandle>& w =
5484 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5485 MAXIMUM_OBSCURING_OPACITY);
5486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005487
5488 touch();
5489
5490 mTouchWindow->consumeAnyMotionDown();
5491}
5492
5493TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005494 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005495 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5496 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5498
5499 touch();
5500
5501 mTouchWindow->assertNoEvents();
5502}
5503
5504TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5505 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5506 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005507 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5508 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005509 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005510 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5511 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5513
5514 touch();
5515
5516 mTouchWindow->assertNoEvents();
5517}
5518
5519TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5520 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5521 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005522 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5523 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005524 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005525 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5526 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5528
5529 touch();
5530
5531 mTouchWindow->consumeAnyMotionDown();
5532}
5533
5534TEST_F(InputDispatcherUntrustedTouchesTest,
5535 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5536 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005537 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5538 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005539 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005540 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5541 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5543
5544 touch();
5545
5546 mTouchWindow->consumeAnyMotionDown();
5547}
5548
5549TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5550 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005551 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5552 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005553 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005554 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5555 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005557
5558 touch();
5559
5560 mTouchWindow->assertNoEvents();
5561}
5562
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005563TEST_F(InputDispatcherUntrustedTouchesTest,
5564 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5565 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005566 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5567 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005568 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005569 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5570 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5572
5573 touch();
5574
5575 mTouchWindow->assertNoEvents();
5576}
5577
5578TEST_F(InputDispatcherUntrustedTouchesTest,
5579 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5580 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005581 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5582 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005583 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005584 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5585 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5587
5588 touch();
5589
5590 mTouchWindow->consumeAnyMotionDown();
5591}
5592
5593TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5594 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005595 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5596 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5598
5599 touch();
5600
5601 mTouchWindow->consumeAnyMotionDown();
5602}
5603
5604TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5605 const sp<FakeWindowHandle>& w =
5606 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5608
5609 touch();
5610
5611 mTouchWindow->consumeAnyMotionDown();
5612}
5613
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005614TEST_F(InputDispatcherUntrustedTouchesTest,
5615 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5616 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5617 const sp<FakeWindowHandle>& w =
5618 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5620
5621 touch();
5622
5623 mTouchWindow->assertNoEvents();
5624}
5625
5626TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5627 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5628 const sp<FakeWindowHandle>& w =
5629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5631
5632 touch();
5633
5634 mTouchWindow->consumeAnyMotionDown();
5635}
5636
5637TEST_F(InputDispatcherUntrustedTouchesTest,
5638 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5639 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5640 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005641 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5642 OPACITY_ABOVE_THRESHOLD);
5643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5644
5645 touch();
5646
5647 mTouchWindow->consumeAnyMotionDown();
5648}
5649
5650TEST_F(InputDispatcherUntrustedTouchesTest,
5651 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5652 const sp<FakeWindowHandle>& w1 =
5653 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5654 OPACITY_BELOW_THRESHOLD);
5655 const sp<FakeWindowHandle>& w2 =
5656 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5657 OPACITY_BELOW_THRESHOLD);
5658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5659
5660 touch();
5661
5662 mTouchWindow->assertNoEvents();
5663}
5664
5665/**
5666 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5667 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5668 * (which alone would result in allowing touches) does not affect the blocking behavior.
5669 */
5670TEST_F(InputDispatcherUntrustedTouchesTest,
5671 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5672 const sp<FakeWindowHandle>& wB =
5673 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5674 OPACITY_BELOW_THRESHOLD);
5675 const sp<FakeWindowHandle>& wC =
5676 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5677 OPACITY_BELOW_THRESHOLD);
5678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5679
5680 touch();
5681
5682 mTouchWindow->assertNoEvents();
5683}
5684
5685/**
5686 * This test is testing that a window from a different UID but with same application token doesn't
5687 * block the touch. Apps can share the application token for close UI collaboration for example.
5688 */
5689TEST_F(InputDispatcherUntrustedTouchesTest,
5690 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5691 const sp<FakeWindowHandle>& w =
5692 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5693 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5695
5696 touch();
5697
5698 mTouchWindow->consumeAnyMotionDown();
5699}
5700
arthurhungb89ccb02020-12-30 16:19:01 +08005701class InputDispatcherDragTests : public InputDispatcherTest {
5702protected:
5703 std::shared_ptr<FakeApplicationHandle> mApp;
5704 sp<FakeWindowHandle> mWindow;
5705 sp<FakeWindowHandle> mSecondWindow;
5706 sp<FakeWindowHandle> mDragWindow;
5707
5708 void SetUp() override {
5709 InputDispatcherTest::SetUp();
5710 mApp = std::make_shared<FakeApplicationHandle>();
5711 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5712 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005713 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005714
5715 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5716 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005717 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005718
5719 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5721 }
5722
5723 // Start performing drag, we will create a drag window and transfer touch to it.
5724 void performDrag() {
5725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5727 {50, 50}))
5728 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5729
5730 // Window should receive motion event.
5731 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5732
5733 // The drag window covers the entire display
5734 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5735 mDispatcher->setInputWindows(
5736 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5737
5738 // Transfer touch focus to the drag window
5739 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5740 true /* isDragDrop */);
5741 mWindow->consumeMotionCancel();
5742 mDragWindow->consumeMotionDown();
5743 }
arthurhung6d4bed92021-03-17 11:59:33 +08005744
5745 // Start performing drag, we will create a drag window and transfer touch to it.
5746 void performStylusDrag() {
5747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5748 injectMotionEvent(mDispatcher,
5749 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5750 AINPUT_SOURCE_STYLUS)
5751 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5752 .pointer(PointerBuilder(0,
5753 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5754 .x(50)
5755 .y(50))
5756 .build()));
5757 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5758
5759 // The drag window covers the entire display
5760 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5761 mDispatcher->setInputWindows(
5762 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5763
5764 // Transfer touch focus to the drag window
5765 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5766 true /* isDragDrop */);
5767 mWindow->consumeMotionCancel();
5768 mDragWindow->consumeMotionDown();
5769 }
arthurhungb89ccb02020-12-30 16:19:01 +08005770};
5771
5772TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5773 performDrag();
5774
5775 // Move on window.
5776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5777 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5778 ADISPLAY_ID_DEFAULT, {50, 50}))
5779 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5780 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5781 mWindow->consumeDragEvent(false, 50, 50);
5782 mSecondWindow->assertNoEvents();
5783
5784 // Move to another window.
5785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5786 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5787 ADISPLAY_ID_DEFAULT, {150, 50}))
5788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5789 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5790 mWindow->consumeDragEvent(true, 150, 50);
5791 mSecondWindow->consumeDragEvent(false, 50, 50);
5792
5793 // Move back to original window.
5794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5795 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5796 ADISPLAY_ID_DEFAULT, {50, 50}))
5797 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5798 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5799 mWindow->consumeDragEvent(false, 50, 50);
5800 mSecondWindow->consumeDragEvent(true, -50, 50);
5801
5802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5803 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5804 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5805 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5806 mWindow->assertNoEvents();
5807 mSecondWindow->assertNoEvents();
5808}
5809
arthurhungf452d0b2021-01-06 00:19:52 +08005810TEST_F(InputDispatcherDragTests, DragAndDrop) {
5811 performDrag();
5812
5813 // Move on window.
5814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5815 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5816 ADISPLAY_ID_DEFAULT, {50, 50}))
5817 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5818 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5819 mWindow->consumeDragEvent(false, 50, 50);
5820 mSecondWindow->assertNoEvents();
5821
5822 // Move to another window.
5823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5824 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5825 ADISPLAY_ID_DEFAULT, {150, 50}))
5826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5827 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5828 mWindow->consumeDragEvent(true, 150, 50);
5829 mSecondWindow->consumeDragEvent(false, 50, 50);
5830
5831 // drop to another window.
5832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5833 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5834 {150, 50}))
5835 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5836 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5837 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5838 mWindow->assertNoEvents();
5839 mSecondWindow->assertNoEvents();
5840}
5841
arthurhung6d4bed92021-03-17 11:59:33 +08005842TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5843 performStylusDrag();
5844
5845 // Move on window and keep button pressed.
5846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5847 injectMotionEvent(mDispatcher,
5848 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5849 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5850 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5851 .x(50)
5852 .y(50))
5853 .build()))
5854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5855 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5856 mWindow->consumeDragEvent(false, 50, 50);
5857 mSecondWindow->assertNoEvents();
5858
5859 // Move to another window and release button, expect to drop item.
5860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5861 injectMotionEvent(mDispatcher,
5862 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5863 .buttonState(0)
5864 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5865 .x(150)
5866 .y(50))
5867 .build()))
5868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5869 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5870 mWindow->assertNoEvents();
5871 mSecondWindow->assertNoEvents();
5872 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5873
5874 // nothing to the window.
5875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5876 injectMotionEvent(mDispatcher,
5877 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5878 .buttonState(0)
5879 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5880 .x(150)
5881 .y(50))
5882 .build()))
5883 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5884 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5885 mWindow->assertNoEvents();
5886 mSecondWindow->assertNoEvents();
5887}
5888
Arthur Hung6d0571e2021-04-09 20:18:16 +08005889TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5890 performDrag();
5891
5892 // Set second window invisible.
5893 mSecondWindow->setVisible(false);
5894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5895
5896 // Move on window.
5897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5898 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5899 ADISPLAY_ID_DEFAULT, {50, 50}))
5900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5901 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5902 mWindow->consumeDragEvent(false, 50, 50);
5903 mSecondWindow->assertNoEvents();
5904
5905 // Move to another window.
5906 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5907 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5908 ADISPLAY_ID_DEFAULT, {150, 50}))
5909 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5910 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5911 mWindow->consumeDragEvent(true, 150, 50);
5912 mSecondWindow->assertNoEvents();
5913
5914 // drop to another window.
5915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5916 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5917 {150, 50}))
5918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5919 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5920 mFakePolicy->assertDropTargetEquals(nullptr);
5921 mWindow->assertNoEvents();
5922 mSecondWindow->assertNoEvents();
5923}
5924
Vishnu Nair062a8672021-09-03 16:07:44 -07005925class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5926
5927TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5928 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5929 sp<FakeWindowHandle> window =
5930 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5931 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5932 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5933 window->setFocusable(true);
5934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5935 setFocusedWindow(window);
5936 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5937
5938 // With the flag set, window should not get any input
5939 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5940 mDispatcher->notifyKey(&keyArgs);
5941 window->assertNoEvents();
5942
5943 NotifyMotionArgs motionArgs =
5944 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5945 ADISPLAY_ID_DEFAULT);
5946 mDispatcher->notifyMotion(&motionArgs);
5947 window->assertNoEvents();
5948
5949 // With the flag cleared, the window should get input
5950 window->setInputFeatures({});
5951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5952
5953 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5954 mDispatcher->notifyKey(&keyArgs);
5955 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5956
5957 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5958 ADISPLAY_ID_DEFAULT);
5959 mDispatcher->notifyMotion(&motionArgs);
5960 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5961 window->assertNoEvents();
5962}
5963
5964TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5965 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5966 std::make_shared<FakeApplicationHandle>();
5967 sp<FakeWindowHandle> obscuringWindow =
5968 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5969 ADISPLAY_ID_DEFAULT);
5970 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5971 obscuringWindow->setOwnerInfo(111, 111);
5972 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5974 sp<FakeWindowHandle> window =
5975 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5976 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5977 window->setOwnerInfo(222, 222);
5978 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5979 window->setFocusable(true);
5980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5981 setFocusedWindow(window);
5982 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5983
5984 // With the flag set, window should not get any input
5985 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5986 mDispatcher->notifyKey(&keyArgs);
5987 window->assertNoEvents();
5988
5989 NotifyMotionArgs motionArgs =
5990 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5991 ADISPLAY_ID_DEFAULT);
5992 mDispatcher->notifyMotion(&motionArgs);
5993 window->assertNoEvents();
5994
5995 // With the flag cleared, the window should get input
5996 window->setInputFeatures({});
5997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5998
5999 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6000 mDispatcher->notifyKey(&keyArgs);
6001 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6002
6003 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6004 ADISPLAY_ID_DEFAULT);
6005 mDispatcher->notifyMotion(&motionArgs);
6006 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6007 window->assertNoEvents();
6008}
6009
6010TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6011 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6012 std::make_shared<FakeApplicationHandle>();
6013 sp<FakeWindowHandle> obscuringWindow =
6014 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6015 ADISPLAY_ID_DEFAULT);
6016 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6017 obscuringWindow->setOwnerInfo(111, 111);
6018 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6019 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6020 sp<FakeWindowHandle> window =
6021 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6022 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6023 window->setOwnerInfo(222, 222);
6024 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6025 window->setFocusable(true);
6026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6027 setFocusedWindow(window);
6028 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6029
6030 // With the flag set, window should not get any input
6031 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6032 mDispatcher->notifyKey(&keyArgs);
6033 window->assertNoEvents();
6034
6035 NotifyMotionArgs motionArgs =
6036 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6037 ADISPLAY_ID_DEFAULT);
6038 mDispatcher->notifyMotion(&motionArgs);
6039 window->assertNoEvents();
6040
6041 // When the window is no longer obscured because it went on top, it should get input
6042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6043
6044 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6045 mDispatcher->notifyKey(&keyArgs);
6046 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6047
6048 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6049 ADISPLAY_ID_DEFAULT);
6050 mDispatcher->notifyMotion(&motionArgs);
6051 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6052 window->assertNoEvents();
6053}
6054
Antonio Kantekf16f2832021-09-28 04:39:20 +00006055class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6056protected:
6057 std::shared_ptr<FakeApplicationHandle> mApp;
6058 sp<FakeWindowHandle> mWindow;
6059 sp<FakeWindowHandle> mSecondWindow;
6060
6061 void SetUp() override {
6062 InputDispatcherTest::SetUp();
6063
6064 mApp = std::make_shared<FakeApplicationHandle>();
6065 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6066 mWindow->setFocusable(true);
6067 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6068 mSecondWindow->setFocusable(true);
6069
6070 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6072
6073 setFocusedWindow(mWindow);
6074 mWindow->consumeFocusEvent(true);
6075 }
6076
6077 void changeAndVerifyTouchMode(bool inTouchMode) {
6078 mDispatcher->setInTouchMode(inTouchMode);
6079 mWindow->consumeTouchModeEvent(inTouchMode);
6080 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6081 }
6082};
6083
6084TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6085 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6086}
6087
6088TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6089 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6090 mWindow->assertNoEvents();
6091 mSecondWindow->assertNoEvents();
6092}
6093
Garfield Tane84e6f92019-08-29 17:28:41 -07006094} // namespace android::inputdispatcher