blob: ba0ce954586d46fb27573bbe6383369274e937a1 [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
Arthur Hungb3307ee2021-10-14 10:57:37 +00002844TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2845 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2846 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2847 true /*isGestureMonitor*/);
2848
2849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2852 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2853}
2854
chaviw81e2bb92019-12-18 15:03:51 -08002855TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002856 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002857 sp<FakeWindowHandle> window =
2858 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2859
Arthur Hung72d8dc32020-03-28 00:48:39 +00002860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002861
2862 NotifyMotionArgs motionArgs =
2863 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2864 ADISPLAY_ID_DEFAULT);
2865
2866 mDispatcher->notifyMotion(&motionArgs);
2867 // Window should receive motion down event.
2868 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2869
2870 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002871 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002872 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2873 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2874 motionArgs.pointerCoords[0].getX() - 10);
2875
2876 mDispatcher->notifyMotion(&motionArgs);
2877 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2878 0 /*expectedFlags*/);
2879}
2880
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002881/**
2882 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2883 * the device default right away. In the test scenario, we check both the default value,
2884 * and the action of enabling / disabling.
2885 */
2886TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002887 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002888 sp<FakeWindowHandle> window =
2889 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2890
2891 // Set focused application.
2892 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002893 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002894
2895 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002897 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002898 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2899
2900 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002901 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002903 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2904
2905 SCOPED_TRACE("Disable touch mode");
2906 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002907 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002908 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002910 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002911 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2912
2913 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002914 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002916 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2917
2918 SCOPED_TRACE("Enable touch mode again");
2919 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002920 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002921 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002923 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002924 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2925
2926 window->assertNoEvents();
2927}
2928
Gang Wange9087892020-01-07 12:17:14 -05002929TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002930 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002931 sp<FakeWindowHandle> window =
2932 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2933
2934 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002935 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002936
Arthur Hung72d8dc32020-03-28 00:48:39 +00002937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002938 setFocusedWindow(window);
2939
Gang Wange9087892020-01-07 12:17:14 -05002940 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2941
2942 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2943 mDispatcher->notifyKey(&keyArgs);
2944
2945 InputEvent* event = window->consume();
2946 ASSERT_NE(event, nullptr);
2947
2948 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2949 ASSERT_NE(verified, nullptr);
2950 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2951
2952 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2953 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2954 ASSERT_EQ(keyArgs.source, verified->source);
2955 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2956
2957 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2958
2959 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2960 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002961 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2962 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2963 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2964 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2965 ASSERT_EQ(0, verifiedKey.repeatCount);
2966}
2967
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002968TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002969 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002970 sp<FakeWindowHandle> window =
2971 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2972
2973 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2974
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002975 ui::Transform transform;
2976 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
2977
2978 gui::DisplayInfo displayInfo;
2979 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
2980 displayInfo.transform = transform;
2981
2982 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002983
2984 NotifyMotionArgs motionArgs =
2985 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2986 ADISPLAY_ID_DEFAULT);
2987 mDispatcher->notifyMotion(&motionArgs);
2988
2989 InputEvent* event = window->consume();
2990 ASSERT_NE(event, nullptr);
2991
2992 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2993 ASSERT_NE(verified, nullptr);
2994 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2995
2996 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2997 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2998 EXPECT_EQ(motionArgs.source, verified->source);
2999 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3000
3001 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3002
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003003 const vec2 rawXY =
3004 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3005 motionArgs.pointerCoords[0].getXYValue());
3006 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3007 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003008 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3009 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3010 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3011 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3012 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3013}
3014
Prabir Pradhan664834b2021-05-20 16:00:42 -07003015TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09003016 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3017 sp<FakeWindowHandle> window =
3018 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3019 const std::string name = window->getName();
3020
3021 // Window gets transformed by offset values.
3022 window->setWindowOffset(500.0f, 500.0f);
3023
3024 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3025 window->setFocusable(true);
3026
3027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3028
3029 // First, we set focused window so that focusedWindowHandle is not null.
3030 setFocusedWindow(window);
3031
3032 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
3033 window->consumeFocusEvent(true);
3034
Prabir Pradhan664834b2021-05-20 16:00:42 -07003035 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
3036 AMOTION_EVENT_ACTION_DOWN),
3037 std::pair(AINPUT_SOURCE_JOYSTICK,
3038 AMOTION_EVENT_ACTION_MOVE)};
3039 for (const auto& [source, action] : nonTransformedSources) {
3040 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08003041 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09003042
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003043 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08003044 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09003045
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003046 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07003047 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08003048 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09003049
Prabir Pradhanbd527712021-03-09 19:17:09 -08003050 float expectedX = motionArgs.pointerCoords[0].getX();
3051 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09003052
Prabir Pradhanbd527712021-03-09 19:17:09 -08003053 // Ensure the axis values from the final motion event are not transformed.
3054 EXPECT_EQ(expectedX, motionEvent.getX(0))
3055 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
3056 << motionEvent.getX(0);
3057 EXPECT_EQ(expectedY, motionEvent.getY(0))
3058 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
3059 << motionEvent.getY(0);
3060 // Ensure the raw and transformed axis values for the motion event are the same.
3061 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
3062 << "expected raw and transformed X-axis values to be equal";
3063 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
3064 << "expected raw and transformed Y-axis values to be equal";
3065 }
yunho.shinf4a80b82020-11-16 21:13:57 +09003066}
3067
chaviw09c8d2d2020-08-24 15:48:26 -07003068/**
3069 * Ensure that separate calls to sign the same data are generating the same key.
3070 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3071 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3072 * tests.
3073 */
3074TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3075 KeyEvent event = getTestKeyEvent();
3076 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3077
3078 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3079 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3080 ASSERT_EQ(hmac1, hmac2);
3081}
3082
3083/**
3084 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3085 */
3086TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3087 KeyEvent event = getTestKeyEvent();
3088 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3089 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3090
3091 verifiedEvent.deviceId += 1;
3092 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3093
3094 verifiedEvent.source += 1;
3095 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3096
3097 verifiedEvent.eventTimeNanos += 1;
3098 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3099
3100 verifiedEvent.displayId += 1;
3101 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3102
3103 verifiedEvent.action += 1;
3104 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3105
3106 verifiedEvent.downTimeNanos += 1;
3107 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3108
3109 verifiedEvent.flags += 1;
3110 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3111
3112 verifiedEvent.keyCode += 1;
3113 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3114
3115 verifiedEvent.scanCode += 1;
3116 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3117
3118 verifiedEvent.metaState += 1;
3119 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3120
3121 verifiedEvent.repeatCount += 1;
3122 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3123}
3124
Vishnu Nair958da932020-08-21 17:12:37 -07003125TEST_F(InputDispatcherTest, SetFocusedWindow) {
3126 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3127 sp<FakeWindowHandle> windowTop =
3128 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3129 sp<FakeWindowHandle> windowSecond =
3130 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3132
3133 // Top window is also focusable but is not granted focus.
3134 windowTop->setFocusable(true);
3135 windowSecond->setFocusable(true);
3136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3137 setFocusedWindow(windowSecond);
3138
3139 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3141 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003142
3143 // Focused window should receive event.
3144 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3145 windowTop->assertNoEvents();
3146}
3147
3148TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3149 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3150 sp<FakeWindowHandle> window =
3151 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3153
3154 window->setFocusable(true);
3155 // Release channel for window is no longer valid.
3156 window->releaseChannel();
3157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3158 setFocusedWindow(window);
3159
3160 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003161 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3162 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003163
3164 // window channel is invalid, so it should not receive any input event.
3165 window->assertNoEvents();
3166}
3167
3168TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3169 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3170 sp<FakeWindowHandle> window =
3171 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3172 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3173
3174 // Window is not focusable.
3175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3176 setFocusedWindow(window);
3177
3178 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003179 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3180 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003181
3182 // window is invalid, so it should not receive any input event.
3183 window->assertNoEvents();
3184}
3185
3186TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3187 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3188 sp<FakeWindowHandle> windowTop =
3189 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3190 sp<FakeWindowHandle> windowSecond =
3191 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3192 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3193
3194 windowTop->setFocusable(true);
3195 windowSecond->setFocusable(true);
3196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3197 setFocusedWindow(windowTop);
3198 windowTop->consumeFocusEvent(true);
3199
3200 setFocusedWindow(windowSecond, windowTop);
3201 windowSecond->consumeFocusEvent(true);
3202 windowTop->consumeFocusEvent(false);
3203
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003204 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3205 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003206
3207 // Focused window should receive event.
3208 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3209}
3210
3211TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3213 sp<FakeWindowHandle> windowTop =
3214 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3215 sp<FakeWindowHandle> windowSecond =
3216 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3217 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3218
3219 windowTop->setFocusable(true);
3220 windowSecond->setFocusable(true);
3221 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3222 setFocusedWindow(windowSecond, windowTop);
3223
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003224 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3225 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003226
3227 // Event should be dropped.
3228 windowTop->assertNoEvents();
3229 windowSecond->assertNoEvents();
3230}
3231
3232TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3233 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3234 sp<FakeWindowHandle> window =
3235 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3236 sp<FakeWindowHandle> previousFocusedWindow =
3237 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3238 ADISPLAY_ID_DEFAULT);
3239 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3240
3241 window->setFocusable(true);
3242 previousFocusedWindow->setFocusable(true);
3243 window->setVisible(false);
3244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3245 setFocusedWindow(previousFocusedWindow);
3246 previousFocusedWindow->consumeFocusEvent(true);
3247
3248 // Requesting focus on invisible window takes focus from currently focused window.
3249 setFocusedWindow(window);
3250 previousFocusedWindow->consumeFocusEvent(false);
3251
3252 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003253 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003254 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003255 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003256
3257 // Window does not get focus event or key down.
3258 window->assertNoEvents();
3259
3260 // Window becomes visible.
3261 window->setVisible(true);
3262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3263
3264 // Window receives focus event.
3265 window->consumeFocusEvent(true);
3266 // Focused window receives key down.
3267 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3268}
3269
Vishnu Nair599f1412021-06-21 10:39:58 -07003270TEST_F(InputDispatcherTest, DisplayRemoved) {
3271 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3272 sp<FakeWindowHandle> window =
3273 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3274 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3275
3276 // window is granted focus.
3277 window->setFocusable(true);
3278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3279 setFocusedWindow(window);
3280 window->consumeFocusEvent(true);
3281
3282 // When a display is removed window loses focus.
3283 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3284 window->consumeFocusEvent(false);
3285}
3286
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003287/**
3288 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3289 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3290 * of the 'slipperyEnterWindow'.
3291 *
3292 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3293 * a way so that the touched location is no longer covered by the top window.
3294 *
3295 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3296 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3297 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3298 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3299 * with ACTION_DOWN).
3300 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3301 * window moved itself away from the touched location and had Flag::SLIPPERY.
3302 *
3303 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3304 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3305 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3306 *
3307 * In this test, we ensure that the event received by the bottom window has
3308 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3309 */
3310TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3311 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3312 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3313
3314 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3315 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3316
3317 sp<FakeWindowHandle> slipperyExitWindow =
3318 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003319 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003320 // Make sure this one overlaps the bottom window
3321 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3322 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3323 // one. Windows with the same owner are not considered to be occluding each other.
3324 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3325
3326 sp<FakeWindowHandle> slipperyEnterWindow =
3327 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3328 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3329
3330 mDispatcher->setInputWindows(
3331 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3332
3333 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3334 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3335 ADISPLAY_ID_DEFAULT, {{50, 50}});
3336 mDispatcher->notifyMotion(&args);
3337 slipperyExitWindow->consumeMotionDown();
3338 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3339 mDispatcher->setInputWindows(
3340 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3341
3342 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3343 ADISPLAY_ID_DEFAULT, {{51, 51}});
3344 mDispatcher->notifyMotion(&args);
3345
3346 slipperyExitWindow->consumeMotionCancel();
3347
3348 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3349 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3350}
3351
Garfield Tan1c7bc862020-01-28 13:24:04 -08003352class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3353protected:
3354 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3355 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3356
Chris Yea209fde2020-07-22 13:54:51 -07003357 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003358 sp<FakeWindowHandle> mWindow;
3359
3360 virtual void SetUp() override {
3361 mFakePolicy = new FakeInputDispatcherPolicy();
3362 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003363 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003364 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3365 ASSERT_EQ(OK, mDispatcher->start());
3366
3367 setUpWindow();
3368 }
3369
3370 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003371 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003372 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3373
Vishnu Nair47074b82020-08-14 11:54:47 -07003374 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003376 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003377 mWindow->consumeFocusEvent(true);
3378 }
3379
Chris Ye2ad95392020-09-01 13:44:44 -07003380 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003381 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003382 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003383 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3384 mDispatcher->notifyKey(&keyArgs);
3385
3386 // Window should receive key down event.
3387 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3388 }
3389
3390 void expectKeyRepeatOnce(int32_t repeatCount) {
3391 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3392 InputEvent* repeatEvent = mWindow->consume();
3393 ASSERT_NE(nullptr, repeatEvent);
3394
3395 uint32_t eventType = repeatEvent->getType();
3396 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3397
3398 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3399 uint32_t eventAction = repeatKeyEvent->getAction();
3400 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3401 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3402 }
3403
Chris Ye2ad95392020-09-01 13:44:44 -07003404 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003405 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003406 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003407 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3408 mDispatcher->notifyKey(&keyArgs);
3409
3410 // Window should receive key down event.
3411 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3412 0 /*expectedFlags*/);
3413 }
3414};
3415
3416TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003417 sendAndConsumeKeyDown(1 /* deviceId */);
3418 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3419 expectKeyRepeatOnce(repeatCount);
3420 }
3421}
3422
3423TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3424 sendAndConsumeKeyDown(1 /* deviceId */);
3425 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3426 expectKeyRepeatOnce(repeatCount);
3427 }
3428 sendAndConsumeKeyDown(2 /* deviceId */);
3429 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003430 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3431 expectKeyRepeatOnce(repeatCount);
3432 }
3433}
3434
3435TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003436 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003437 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003438 sendAndConsumeKeyUp(1 /* deviceId */);
3439 mWindow->assertNoEvents();
3440}
3441
3442TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3443 sendAndConsumeKeyDown(1 /* deviceId */);
3444 expectKeyRepeatOnce(1 /*repeatCount*/);
3445 sendAndConsumeKeyDown(2 /* deviceId */);
3446 expectKeyRepeatOnce(1 /*repeatCount*/);
3447 // Stale key up from device 1.
3448 sendAndConsumeKeyUp(1 /* deviceId */);
3449 // Device 2 is still down, keep repeating
3450 expectKeyRepeatOnce(2 /*repeatCount*/);
3451 expectKeyRepeatOnce(3 /*repeatCount*/);
3452 // Device 2 key up
3453 sendAndConsumeKeyUp(2 /* deviceId */);
3454 mWindow->assertNoEvents();
3455}
3456
3457TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3458 sendAndConsumeKeyDown(1 /* deviceId */);
3459 expectKeyRepeatOnce(1 /*repeatCount*/);
3460 sendAndConsumeKeyDown(2 /* deviceId */);
3461 expectKeyRepeatOnce(1 /*repeatCount*/);
3462 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3463 sendAndConsumeKeyUp(2 /* deviceId */);
3464 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003465 mWindow->assertNoEvents();
3466}
3467
liushenxiang42232912021-05-21 20:24:09 +08003468TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3469 sendAndConsumeKeyDown(DEVICE_ID);
3470 expectKeyRepeatOnce(1 /*repeatCount*/);
3471 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3472 mDispatcher->notifyDeviceReset(&args);
3473 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3474 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3475 mWindow->assertNoEvents();
3476}
3477
Garfield Tan1c7bc862020-01-28 13:24:04 -08003478TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003479 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003480 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3481 InputEvent* repeatEvent = mWindow->consume();
3482 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3483 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3484 IdGenerator::getSource(repeatEvent->getId()));
3485 }
3486}
3487
3488TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003489 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003490
3491 std::unordered_set<int32_t> idSet;
3492 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3493 InputEvent* repeatEvent = mWindow->consume();
3494 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3495 int32_t id = repeatEvent->getId();
3496 EXPECT_EQ(idSet.end(), idSet.find(id));
3497 idSet.insert(id);
3498 }
3499}
3500
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003501/* Test InputDispatcher for MultiDisplay */
3502class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3503public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003504 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003505 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003506
Chris Yea209fde2020-07-22 13:54:51 -07003507 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003508 windowInPrimary =
3509 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003510
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003511 // Set focus window for primary display, but focused display would be second one.
3512 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003513 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003515 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003516 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003517
Chris Yea209fde2020-07-22 13:54:51 -07003518 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003519 windowInSecondary =
3520 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003521 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003522 // Set focus display to second one.
3523 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3524 // Set focus window for second display.
3525 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003526 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003527 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003528 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003529 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003530 }
3531
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003532 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003533 InputDispatcherTest::TearDown();
3534
Chris Yea209fde2020-07-22 13:54:51 -07003535 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003536 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003537 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003538 windowInSecondary.clear();
3539 }
3540
3541protected:
Chris Yea209fde2020-07-22 13:54:51 -07003542 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003543 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003544 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003545 sp<FakeWindowHandle> windowInSecondary;
3546};
3547
3548TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3549 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3551 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003553 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003554 windowInSecondary->assertNoEvents();
3555
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003556 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003561 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003562}
3563
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003564TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003565 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3567 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003569 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003570 windowInSecondary->assertNoEvents();
3571
3572 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003574 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003575 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003576 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003578 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003579 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003580
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003581 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003582 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3583 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003584
3585 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003586 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003587 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003588 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003589 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003590 windowInSecondary->assertNoEvents();
3591}
3592
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003593// Test per-display input monitors for motion event.
3594TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003595 FakeMonitorReceiver monitorInPrimary =
3596 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3597 FakeMonitorReceiver monitorInSecondary =
3598 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599
3600 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3602 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3603 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003604 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003605 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003606 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003607 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003608
3609 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
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(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003616 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003617
3618 // Test inject a non-pointer motion event.
3619 // If specific a display, it will dispatch to the focused window of particular display,
3620 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3622 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003624 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003625 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003626 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003627 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003628}
3629
3630// Test per-display input monitors for key event.
3631TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003632 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003633 FakeMonitorReceiver monitorInPrimary =
3634 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3635 FakeMonitorReceiver monitorInSecondary =
3636 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003637
3638 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3640 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003641 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003642 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003643 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003644 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003645}
3646
Vishnu Nair958da932020-08-21 17:12:37 -07003647TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3648 sp<FakeWindowHandle> secondWindowInPrimary =
3649 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3650 secondWindowInPrimary->setFocusable(true);
3651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3652 setFocusedWindow(secondWindowInPrimary);
3653 windowInPrimary->consumeFocusEvent(false);
3654 secondWindowInPrimary->consumeFocusEvent(true);
3655
3656 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3658 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003659 windowInPrimary->assertNoEvents();
3660 windowInSecondary->assertNoEvents();
3661 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3662}
3663
Jackal Guof9696682018-10-05 12:23:23 +08003664class InputFilterTest : public InputDispatcherTest {
3665protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003666 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3667 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003668 NotifyMotionArgs motionArgs;
3669
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003670 motionArgs =
3671 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003672 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003673 motionArgs =
3674 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003675 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003676 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003677 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003678 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3679 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003680 } else {
3681 mFakePolicy->assertFilterInputEventWasNotCalled();
3682 }
3683 }
3684
3685 void testNotifyKey(bool expectToBeFiltered) {
3686 NotifyKeyArgs keyArgs;
3687
3688 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3689 mDispatcher->notifyKey(&keyArgs);
3690 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3691 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003692 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003693
3694 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003695 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003696 } else {
3697 mFakePolicy->assertFilterInputEventWasNotCalled();
3698 }
3699 }
3700};
3701
3702// Test InputFilter for MotionEvent
3703TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3704 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3705 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3706 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3707
3708 // Enable InputFilter
3709 mDispatcher->setInputFilterEnabled(true);
3710 // Test touch on both primary and second display, and check if both events are filtered.
3711 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3712 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3713
3714 // Disable InputFilter
3715 mDispatcher->setInputFilterEnabled(false);
3716 // Test touch on both primary and second display, and check if both events aren't filtered.
3717 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3718 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3719}
3720
3721// Test InputFilter for KeyEvent
3722TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3723 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3724 testNotifyKey(/*expectToBeFiltered*/ false);
3725
3726 // Enable InputFilter
3727 mDispatcher->setInputFilterEnabled(true);
3728 // Send a key event, and check if it is filtered.
3729 testNotifyKey(/*expectToBeFiltered*/ true);
3730
3731 // Disable InputFilter
3732 mDispatcher->setInputFilterEnabled(false);
3733 // Send a key event, and check if it isn't filtered.
3734 testNotifyKey(/*expectToBeFiltered*/ false);
3735}
3736
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003737// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3738// logical display coordinate space.
3739TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3740 ui::Transform firstDisplayTransform;
3741 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3742 ui::Transform secondDisplayTransform;
3743 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3744
3745 std::vector<gui::DisplayInfo> displayInfos(2);
3746 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3747 displayInfos[0].transform = firstDisplayTransform;
3748 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3749 displayInfos[1].transform = secondDisplayTransform;
3750
3751 mDispatcher->onWindowInfosChanged({}, displayInfos);
3752
3753 // Enable InputFilter
3754 mDispatcher->setInputFilterEnabled(true);
3755
3756 // Ensure the correct transforms are used for the displays.
3757 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3758 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3759}
3760
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003761class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3762protected:
3763 virtual void SetUp() override {
3764 InputDispatcherTest::SetUp();
3765
3766 /**
3767 * We don't need to enable input filter to test the injected event policy, but we enabled it
3768 * here to make the tests more realistic, since this policy only matters when inputfilter is
3769 * on.
3770 */
3771 mDispatcher->setInputFilterEnabled(true);
3772
3773 std::shared_ptr<InputApplicationHandle> application =
3774 std::make_shared<FakeApplicationHandle>();
3775 mWindow =
3776 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3777
3778 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3779 mWindow->setFocusable(true);
3780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3781 setFocusedWindow(mWindow);
3782 mWindow->consumeFocusEvent(true);
3783 }
3784
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003785 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3786 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003787 KeyEvent event;
3788
3789 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3790 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3791 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3792 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3793 const int32_t additionalPolicyFlags =
3794 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3796 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3797 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3798 policyFlags | additionalPolicyFlags));
3799
3800 InputEvent* received = mWindow->consume();
3801 ASSERT_NE(nullptr, received);
3802 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003803 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3804 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3805 ASSERT_EQ(flags, keyEvent.getFlags());
3806 }
3807
3808 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3809 int32_t flags) {
3810 MotionEvent event;
3811 PointerProperties pointerProperties[1];
3812 PointerCoords pointerCoords[1];
3813 pointerProperties[0].clear();
3814 pointerProperties[0].id = 0;
3815 pointerCoords[0].clear();
3816 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3817 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3818
3819 ui::Transform identityTransform;
3820 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3821 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3822 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3823 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3824 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003825 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003826 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003827 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3828
3829 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3831 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3832 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3833 policyFlags | additionalPolicyFlags));
3834
3835 InputEvent* received = mWindow->consume();
3836 ASSERT_NE(nullptr, received);
3837 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3838 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3839 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3840 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003841 }
3842
3843private:
3844 sp<FakeWindowHandle> mWindow;
3845};
3846
3847TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003848 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3849 // filter. Without it, the event will no different from a regularly injected event, and the
3850 // injected device id will be overwritten.
3851 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3852 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003853}
3854
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003855TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003856 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003857 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3858 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3859}
3860
3861TEST_F(InputFilterInjectionPolicyTest,
3862 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3863 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3864 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3865 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003866}
3867
3868TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3869 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003870 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003871}
3872
chaviwfd6d3512019-03-25 13:23:49 -07003873class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003874 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003875 InputDispatcherTest::SetUp();
3876
Chris Yea209fde2020-07-22 13:54:51 -07003877 std::shared_ptr<FakeApplicationHandle> application =
3878 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003879 mUnfocusedWindow =
3880 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003881 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3882 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3883 // window.
chaviw3277faf2021-05-19 16:45:23 -05003884 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003885
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003886 mFocusedWindow =
3887 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3888 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003889 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003890
3891 // Set focused application.
3892 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003893 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003894
3895 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003897 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003898 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003899 }
3900
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003901 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003902 InputDispatcherTest::TearDown();
3903
3904 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003905 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003906 }
3907
3908protected:
3909 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003910 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003911 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003912};
3913
3914// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3915// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3916// the onPointerDownOutsideFocus callback.
3917TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003919 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3920 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003921 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003922 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003923
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003924 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003925 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3926}
3927
3928// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3929// DOWN on the window that doesn't have focus. Ensure no window received the
3930// onPointerDownOutsideFocus callback.
3931TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003933 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003935 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003936
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003937 ASSERT_TRUE(mDispatcher->waitForIdle());
3938 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003939}
3940
3941// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3942// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3943TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3945 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003946 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003947 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003948
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003949 ASSERT_TRUE(mDispatcher->waitForIdle());
3950 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003951}
3952
3953// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3954// DOWN on the window that already has focus. Ensure no window received the
3955// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003956TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003958 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003959 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003960 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003961 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003962
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003963 ASSERT_TRUE(mDispatcher->waitForIdle());
3964 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003965}
3966
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003967// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3968// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3969TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3970 const MotionEvent event =
3971 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3972 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3973 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3974 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3975 .build();
3976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3978 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3979
3980 ASSERT_TRUE(mDispatcher->waitForIdle());
3981 mFakePolicy->assertOnPointerDownWasNotCalled();
3982 // Ensure that the unfocused window did not receive any FOCUS events.
3983 mUnfocusedWindow->assertNoEvents();
3984}
3985
chaviwaf87b3e2019-10-01 16:59:28 -07003986// These tests ensures we can send touch events to a single client when there are multiple input
3987// windows that point to the same client token.
3988class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3989 virtual void SetUp() override {
3990 InputDispatcherTest::SetUp();
3991
Chris Yea209fde2020-07-22 13:54:51 -07003992 std::shared_ptr<FakeApplicationHandle> application =
3993 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003994 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3995 ADISPLAY_ID_DEFAULT);
3996 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3997 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003998 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003999 mWindow1->setFrame(Rect(0, 0, 100, 100));
4000
4001 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4002 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004003 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004004 mWindow2->setFrame(Rect(100, 100, 200, 200));
4005
Arthur Hung72d8dc32020-03-28 00:48:39 +00004006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004007 }
4008
4009protected:
4010 sp<FakeWindowHandle> mWindow1;
4011 sp<FakeWindowHandle> mWindow2;
4012
4013 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004014 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004015 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4016 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004017 }
4018
4019 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4020 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004021 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004022 InputEvent* event = window->consume();
4023
4024 ASSERT_NE(nullptr, event) << name.c_str()
4025 << ": consumer should have returned non-NULL event.";
4026
4027 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4028 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4029 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4030
4031 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004032 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004033
4034 for (size_t i = 0; i < points.size(); i++) {
4035 float expectedX = points[i].x;
4036 float expectedY = points[i].y;
4037
4038 EXPECT_EQ(expectedX, motionEvent.getX(i))
4039 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4040 << ", got " << motionEvent.getX(i);
4041 EXPECT_EQ(expectedY, motionEvent.getY(i))
4042 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4043 << ", got " << motionEvent.getY(i);
4044 }
4045 }
chaviw9eaa22c2020-07-01 16:21:27 -07004046
4047 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4048 std::vector<PointF> expectedPoints) {
4049 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4050 ADISPLAY_ID_DEFAULT, touchedPoints);
4051 mDispatcher->notifyMotion(&motionArgs);
4052
4053 // Always consume from window1 since it's the window that has the InputReceiver
4054 consumeMotionEvent(mWindow1, action, expectedPoints);
4055 }
chaviwaf87b3e2019-10-01 16:59:28 -07004056};
4057
4058TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4059 // Touch Window 1
4060 PointF touchedPoint = {10, 10};
4061 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004062 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004063
4064 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004065 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004066
4067 // Touch Window 2
4068 touchedPoint = {150, 150};
4069 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004070 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004071}
4072
chaviw9eaa22c2020-07-01 16:21:27 -07004073TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4074 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004075 mWindow2->setWindowScale(0.5f, 0.5f);
4076
4077 // Touch Window 1
4078 PointF touchedPoint = {10, 10};
4079 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004080 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004081 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004082 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004083
4084 // Touch Window 2
4085 touchedPoint = {150, 150};
4086 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004087 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4088 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004089
chaviw9eaa22c2020-07-01 16:21:27 -07004090 // Update the transform so rotation is set
4091 mWindow2->setWindowTransform(0, -1, 1, 0);
4092 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4093 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004094}
4095
chaviw9eaa22c2020-07-01 16:21:27 -07004096TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004097 mWindow2->setWindowScale(0.5f, 0.5f);
4098
4099 // Touch Window 1
4100 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4101 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004102 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004103
4104 // Touch Window 2
4105 int32_t actionPointerDown =
4106 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004107 touchedPoints.push_back(PointF{150, 150});
4108 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4109 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004110
chaviw9eaa22c2020-07-01 16:21:27 -07004111 // Release Window 2
4112 int32_t actionPointerUp =
4113 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4114 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4115 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004116
chaviw9eaa22c2020-07-01 16:21:27 -07004117 // Update the transform so rotation is set for Window 2
4118 mWindow2->setWindowTransform(0, -1, 1, 0);
4119 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4120 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004121}
4122
chaviw9eaa22c2020-07-01 16:21:27 -07004123TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004124 mWindow2->setWindowScale(0.5f, 0.5f);
4125
4126 // Touch Window 1
4127 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4128 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004129 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004130
4131 // Touch Window 2
4132 int32_t actionPointerDown =
4133 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004134 touchedPoints.push_back(PointF{150, 150});
4135 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004136
chaviw9eaa22c2020-07-01 16:21:27 -07004137 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004138
4139 // Move both windows
4140 touchedPoints = {{20, 20}, {175, 175}};
4141 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4142 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4143
chaviw9eaa22c2020-07-01 16:21:27 -07004144 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004145
chaviw9eaa22c2020-07-01 16:21:27 -07004146 // Release Window 2
4147 int32_t actionPointerUp =
4148 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4149 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4150 expectedPoints.pop_back();
4151
4152 // Touch Window 2
4153 mWindow2->setWindowTransform(0, -1, 1, 0);
4154 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4155 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4156
4157 // Move both windows
4158 touchedPoints = {{20, 20}, {175, 175}};
4159 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4160 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4161
4162 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004163}
4164
4165TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4166 mWindow1->setWindowScale(0.5f, 0.5f);
4167
4168 // Touch Window 1
4169 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4170 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004171 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004172
4173 // Touch Window 2
4174 int32_t actionPointerDown =
4175 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004176 touchedPoints.push_back(PointF{150, 150});
4177 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004178
chaviw9eaa22c2020-07-01 16:21:27 -07004179 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004180
4181 // Move both windows
4182 touchedPoints = {{20, 20}, {175, 175}};
4183 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4184 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4185
chaviw9eaa22c2020-07-01 16:21:27 -07004186 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004187}
4188
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004189class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4190 virtual void SetUp() override {
4191 InputDispatcherTest::SetUp();
4192
Chris Yea209fde2020-07-22 13:54:51 -07004193 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004194 mApplication->setDispatchingTimeout(20ms);
4195 mWindow =
4196 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4197 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004198 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004199 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004200 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4201 // window.
chaviw3277faf2021-05-19 16:45:23 -05004202 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004203
4204 // Set focused application.
4205 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4206
4207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004208 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004209 mWindow->consumeFocusEvent(true);
4210 }
4211
4212 virtual void TearDown() override {
4213 InputDispatcherTest::TearDown();
4214 mWindow.clear();
4215 }
4216
4217protected:
Chris Yea209fde2020-07-22 13:54:51 -07004218 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004219 sp<FakeWindowHandle> mWindow;
4220 static constexpr PointF WINDOW_LOCATION = {20, 20};
4221
4222 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004224 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4225 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004227 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4228 WINDOW_LOCATION));
4229 }
4230};
4231
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004232// Send a tap and respond, which should not cause an ANR.
4233TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4234 tapOnWindow();
4235 mWindow->consumeMotionDown();
4236 mWindow->consumeMotionUp();
4237 ASSERT_TRUE(mDispatcher->waitForIdle());
4238 mFakePolicy->assertNotifyAnrWasNotCalled();
4239}
4240
4241// Send a regular key and respond, which should not cause an ANR.
4242TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004244 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4245 ASSERT_TRUE(mDispatcher->waitForIdle());
4246 mFakePolicy->assertNotifyAnrWasNotCalled();
4247}
4248
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004249TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4250 mWindow->setFocusable(false);
4251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4252 mWindow->consumeFocusEvent(false);
4253
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004255 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004256 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4257 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004259 // Key will not go to window because we have no focused window.
4260 // The 'no focused window' ANR timer should start instead.
4261
4262 // Now, the focused application goes away.
4263 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4264 // The key should get dropped and there should be no ANR.
4265
4266 ASSERT_TRUE(mDispatcher->waitForIdle());
4267 mFakePolicy->assertNotifyAnrWasNotCalled();
4268}
4269
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004270// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004271// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4272// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004273TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004275 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4276 WINDOW_LOCATION));
4277
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004278 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4279 ASSERT_TRUE(sequenceNum);
4280 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004281 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004282
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004283 mWindow->finishEvent(*sequenceNum);
4284 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4285 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004286 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004287 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004288}
4289
4290// Send a key to the app and have the app not respond right away.
4291TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4292 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004293 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004294 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4295 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004296 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004297 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004298 ASSERT_TRUE(mDispatcher->waitForIdle());
4299}
4300
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004301// We have a focused application, but no focused window
4302TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004303 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4305 mWindow->consumeFocusEvent(false);
4306
4307 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004309 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4310 WINDOW_LOCATION));
4311 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4312 mDispatcher->waitForIdle();
4313 mFakePolicy->assertNotifyAnrWasNotCalled();
4314
4315 // Once a focused event arrives, we get an ANR for this application
4316 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4317 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004318 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004319 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004320 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004321 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004322 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004323 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004324 ASSERT_TRUE(mDispatcher->waitForIdle());
4325}
4326
4327// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004328// Make sure that we don't notify policy twice about the same ANR.
4329TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004330 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4332 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004333
4334 // Once a focused event arrives, we get an ANR for this application
4335 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4336 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004338 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004339 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004340 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004341 const std::chrono::duration appTimeout =
4342 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004343 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004345 std::this_thread::sleep_for(appTimeout);
4346 // ANR should not be raised again. It is up to policy to do that if it desires.
4347 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004348
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004349 // If we now get a focused window, the ANR should stop, but the policy handles that via
4350 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004351 ASSERT_TRUE(mDispatcher->waitForIdle());
4352}
4353
4354// We have a focused application, but no focused window
4355TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004356 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4358 mWindow->consumeFocusEvent(false);
4359
4360 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4364 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004365
4366 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004367 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004368
4369 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004371 ASSERT_TRUE(mDispatcher->waitForIdle());
4372 mWindow->assertNoEvents();
4373}
4374
4375/**
4376 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4377 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4378 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4379 * the ANR mechanism should still work.
4380 *
4381 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4382 * DOWN event, while not responding on the second one.
4383 */
4384TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4385 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4386 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4387 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4388 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4389 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004390 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004391
4392 // Now send ACTION_UP, with identical timestamp
4393 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4394 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4395 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4396 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004398
4399 // We have now sent down and up. Let's consume first event and then ANR on the second.
4400 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4401 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004402 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004403}
4404
4405// If an app is not responding to a key event, gesture monitors should continue to receive
4406// new motion events
4407TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4408 FakeMonitorReceiver monitor =
4409 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4410 true /*isGestureMonitor*/);
4411
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4413 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004414 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004416
4417 // Stuck on the ACTION_UP
4418 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004419 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420
4421 // New tap will go to the gesture monitor, but not to the window
4422 tapOnWindow();
4423 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4424 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4425
4426 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4427 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004428 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004429 mWindow->assertNoEvents();
4430 monitor.assertNoEvents();
4431}
4432
4433// If an app is not responding to a motion event, gesture monitors should continue to receive
4434// new motion events
4435TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4436 FakeMonitorReceiver monitor =
4437 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4438 true /*isGestureMonitor*/);
4439
4440 tapOnWindow();
4441 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4442 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4443
4444 mWindow->consumeMotionDown();
4445 // Stuck on the ACTION_UP
4446 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004447 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448
4449 // New tap will go to the gesture monitor, but not to the window
4450 tapOnWindow();
4451 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4452 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4453
4454 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4455 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004456 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 mWindow->assertNoEvents();
4458 monitor.assertNoEvents();
4459}
4460
4461// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4462// process events, you don't get an anr. When the window later becomes unresponsive again, you
4463// get an ANR again.
4464// 1. tap -> block on ACTION_UP -> receive ANR
4465// 2. consume all pending events (= queue becomes healthy again)
4466// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4467TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4468 tapOnWindow();
4469
4470 mWindow->consumeMotionDown();
4471 // Block on ACTION_UP
4472 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004473 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004474 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4475 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004476 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004477 mWindow->assertNoEvents();
4478
4479 tapOnWindow();
4480 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004481 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482 mWindow->consumeMotionUp();
4483
4484 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004485 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004486 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004487 mWindow->assertNoEvents();
4488}
4489
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004490// If a connection remains unresponsive for a while, make sure policy is only notified once about
4491// it.
4492TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4495 WINDOW_LOCATION));
4496
4497 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004498 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004500 // 'notifyConnectionUnresponsive' should only be called once per connection
4501 mFakePolicy->assertNotifyAnrWasNotCalled();
4502 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004503 mWindow->consumeMotionDown();
4504 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4505 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4506 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004507 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004508 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004509 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510}
4511
4512/**
4513 * If a window is processing a motion event, and then a key event comes in, the key event should
4514 * not to to the focused window until the motion is processed.
4515 *
4516 * Warning!!!
4517 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4518 * and the injection timeout that we specify when injecting the key.
4519 * We must have the injection timeout (10ms) be smaller than
4520 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4521 *
4522 * If that value changes, this test should also change.
4523 */
4524TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4525 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4527
4528 tapOnWindow();
4529 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4530 ASSERT_TRUE(downSequenceNum);
4531 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4532 ASSERT_TRUE(upSequenceNum);
4533 // Don't finish the events yet, and send a key
4534 // Injection will "succeed" because we will eventually give up and send the key to the focused
4535 // window even if motions are still being processed. But because the injection timeout is short,
4536 // we will receive INJECTION_TIMED_OUT as the result.
4537
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004538 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004539 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004540 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4541 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542 // Key will not be sent to the window, yet, because the window is still processing events
4543 // and the key remains pending, waiting for the touch events to be processed
4544 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4545 ASSERT_FALSE(keySequenceNum);
4546
4547 std::this_thread::sleep_for(500ms);
4548 // if we wait long enough though, dispatcher will give up, and still send the key
4549 // to the focused window, even though we have not yet finished the motion event
4550 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4551 mWindow->finishEvent(*downSequenceNum);
4552 mWindow->finishEvent(*upSequenceNum);
4553}
4554
4555/**
4556 * If a window is processing a motion event, and then a key event comes in, the key event should
4557 * not go to the focused window until the motion is processed.
4558 * If then a new motion comes in, then the pending key event should be going to the currently
4559 * focused window right away.
4560 */
4561TEST_F(InputDispatcherSingleWindowAnr,
4562 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4563 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4565
4566 tapOnWindow();
4567 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4568 ASSERT_TRUE(downSequenceNum);
4569 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4570 ASSERT_TRUE(upSequenceNum);
4571 // Don't finish the events yet, and send a key
4572 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004574 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004576 // At this point, key is still pending, and should not be sent to the application yet.
4577 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4578 ASSERT_FALSE(keySequenceNum);
4579
4580 // Now tap down again. It should cause the pending key to go to the focused window right away.
4581 tapOnWindow();
4582 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4583 // the other events yet. We can finish events in any order.
4584 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4585 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4586 mWindow->consumeMotionDown();
4587 mWindow->consumeMotionUp();
4588 mWindow->assertNoEvents();
4589}
4590
4591class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4592 virtual void SetUp() override {
4593 InputDispatcherTest::SetUp();
4594
Chris Yea209fde2020-07-22 13:54:51 -07004595 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004596 mApplication->setDispatchingTimeout(10ms);
4597 mUnfocusedWindow =
4598 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4599 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4600 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4601 // window.
4602 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004603 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4604 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4605 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606
4607 mFocusedWindow =
4608 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004609 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004610 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004611 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612
4613 // Set focused application.
4614 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004615 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616
4617 // Expect one focus window exist in display.
4618 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004619 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620 mFocusedWindow->consumeFocusEvent(true);
4621 }
4622
4623 virtual void TearDown() override {
4624 InputDispatcherTest::TearDown();
4625
4626 mUnfocusedWindow.clear();
4627 mFocusedWindow.clear();
4628 }
4629
4630protected:
Chris Yea209fde2020-07-22 13:54:51 -07004631 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 sp<FakeWindowHandle> mUnfocusedWindow;
4633 sp<FakeWindowHandle> mFocusedWindow;
4634 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4635 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4636 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4637
4638 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4639
4640 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4641
4642private:
4643 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4646 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004648 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4649 location));
4650 }
4651};
4652
4653// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4654// should be ANR'd first.
4655TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
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))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660 mFocusedWindow->consumeMotionDown();
4661 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4662 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4663 // We consumed all events, so no ANR
4664 ASSERT_TRUE(mDispatcher->waitForIdle());
4665 mFakePolicy->assertNotifyAnrWasNotCalled();
4666
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4669 FOCUSED_WINDOW_LOCATION));
4670 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4671 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672
4673 const std::chrono::duration timeout =
4674 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004675 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004676 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4677 // sequence to make it consistent
4678 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004679 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004680 mFocusedWindow->consumeMotionDown();
4681 // This cancel is generated because the connection was unresponsive
4682 mFocusedWindow->consumeMotionCancel();
4683 mFocusedWindow->assertNoEvents();
4684 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004685 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004686 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004687 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688}
4689
4690// If we have 2 windows with identical timeouts that are both unresponsive,
4691// it doesn't matter which order they should have ANR.
4692// But we should receive ANR for both.
4693TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4694 // Set the timeout for unfocused window to match the focused window
4695 mUnfocusedWindow->setDispatchingTimeout(10ms);
4696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4697
4698 tapOnFocusedWindow();
4699 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004700 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4701 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004702
4703 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004704 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4705 mFocusedWindow->getToken() == anrConnectionToken2);
4706 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4707 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004708
4709 ASSERT_TRUE(mDispatcher->waitForIdle());
4710 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004711
4712 mFocusedWindow->consumeMotionDown();
4713 mFocusedWindow->consumeMotionUp();
4714 mUnfocusedWindow->consumeMotionOutside();
4715
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004716 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4717 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004718
4719 // Both applications should be marked as responsive, in any order
4720 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4721 mFocusedWindow->getToken() == responsiveToken2);
4722 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4723 mUnfocusedWindow->getToken() == responsiveToken2);
4724 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725}
4726
4727// If a window is already not responding, the second tap on the same window should be ignored.
4728// We should also log an error to account for the dropped event (not tested here).
4729// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4730TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4731 tapOnFocusedWindow();
4732 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4733 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4734 // Receive the events, but don't respond
4735 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4736 ASSERT_TRUE(downEventSequenceNum);
4737 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4738 ASSERT_TRUE(upEventSequenceNum);
4739 const std::chrono::duration timeout =
4740 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004741 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742
4743 // Tap once again
4744 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004745 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4747 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004748 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4750 FOCUSED_WINDOW_LOCATION));
4751 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4752 // valid touch target
4753 mUnfocusedWindow->assertNoEvents();
4754
4755 // Consume the first tap
4756 mFocusedWindow->finishEvent(*downEventSequenceNum);
4757 mFocusedWindow->finishEvent(*upEventSequenceNum);
4758 ASSERT_TRUE(mDispatcher->waitForIdle());
4759 // The second tap did not go to the focused window
4760 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004761 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004762 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004763 mFakePolicy->assertNotifyAnrWasNotCalled();
4764}
4765
4766// If you tap outside of all windows, there will not be ANR
4767TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004768 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4770 LOCATION_OUTSIDE_ALL_WINDOWS));
4771 ASSERT_TRUE(mDispatcher->waitForIdle());
4772 mFakePolicy->assertNotifyAnrWasNotCalled();
4773}
4774
4775// Since the focused window is paused, tapping on it should not produce any events
4776TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4777 mFocusedWindow->setPaused(true);
4778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4779
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004780 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4782 FOCUSED_WINDOW_LOCATION));
4783
4784 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4785 ASSERT_TRUE(mDispatcher->waitForIdle());
4786 // Should not ANR because the window is paused, and touches shouldn't go to it
4787 mFakePolicy->assertNotifyAnrWasNotCalled();
4788
4789 mFocusedWindow->assertNoEvents();
4790 mUnfocusedWindow->assertNoEvents();
4791}
4792
4793/**
4794 * If a window is processing a motion event, and then a key event comes in, the key event should
4795 * not to to the focused window until the motion is processed.
4796 * If a different window becomes focused at this time, the key should go to that window instead.
4797 *
4798 * Warning!!!
4799 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4800 * and the injection timeout that we specify when injecting the key.
4801 * We must have the injection timeout (10ms) be smaller than
4802 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4803 *
4804 * If that value changes, this test should also change.
4805 */
4806TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4807 // Set a long ANR timeout to prevent it from triggering
4808 mFocusedWindow->setDispatchingTimeout(2s);
4809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4810
4811 tapOnUnfocusedWindow();
4812 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4813 ASSERT_TRUE(downSequenceNum);
4814 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4815 ASSERT_TRUE(upSequenceNum);
4816 // Don't finish the events yet, and send a key
4817 // Injection will succeed because we will eventually give up and send the key to the focused
4818 // window even if motions are still being processed.
4819
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004822 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 // Key will not be sent to the window, yet, because the window is still processing events
4825 // and the key remains pending, waiting for the touch events to be processed
4826 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4827 ASSERT_FALSE(keySequenceNum);
4828
4829 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004830 mFocusedWindow->setFocusable(false);
4831 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004833 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834
4835 // Focus events should precede the key events
4836 mUnfocusedWindow->consumeFocusEvent(true);
4837 mFocusedWindow->consumeFocusEvent(false);
4838
4839 // Finish the tap events, which should unblock dispatcher
4840 mUnfocusedWindow->finishEvent(*downSequenceNum);
4841 mUnfocusedWindow->finishEvent(*upSequenceNum);
4842
4843 // Now that all queues are cleared and no backlog in the connections, the key event
4844 // can finally go to the newly focused "mUnfocusedWindow".
4845 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4846 mFocusedWindow->assertNoEvents();
4847 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004848 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849}
4850
4851// When the touch stream is split across 2 windows, and one of them does not respond,
4852// then ANR should be raised and the touch should be canceled for the unresponsive window.
4853// The other window should not be affected by that.
4854TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4855 // Touch Window 1
4856 NotifyMotionArgs motionArgs =
4857 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4858 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4859 mDispatcher->notifyMotion(&motionArgs);
4860 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4861 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4862
4863 // Touch Window 2
4864 int32_t actionPointerDown =
4865 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4866
4867 motionArgs =
4868 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4869 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4870 mDispatcher->notifyMotion(&motionArgs);
4871
4872 const std::chrono::duration timeout =
4873 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004874 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875
4876 mUnfocusedWindow->consumeMotionDown();
4877 mFocusedWindow->consumeMotionDown();
4878 // Focused window may or may not receive ACTION_MOVE
4879 // But it should definitely receive ACTION_CANCEL due to the ANR
4880 InputEvent* event;
4881 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4882 ASSERT_TRUE(moveOrCancelSequenceNum);
4883 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4884 ASSERT_NE(nullptr, event);
4885 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4886 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4887 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4888 mFocusedWindow->consumeMotionCancel();
4889 } else {
4890 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4891 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004892 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004893 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004894
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895 mUnfocusedWindow->assertNoEvents();
4896 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004897 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898}
4899
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004900/**
4901 * If we have no focused window, and a key comes in, we start the ANR timer.
4902 * The focused application should add a focused window before the timer runs out to prevent ANR.
4903 *
4904 * If the user touches another application during this time, the key should be dropped.
4905 * Next, if a new focused window comes in, without toggling the focused application,
4906 * then no ANR should occur.
4907 *
4908 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4909 * but in some cases the policy may not update the focused application.
4910 */
4911TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4912 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4913 std::make_shared<FakeApplicationHandle>();
4914 focusedApplication->setDispatchingTimeout(60ms);
4915 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4916 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4917 mFocusedWindow->setFocusable(false);
4918
4919 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4920 mFocusedWindow->consumeFocusEvent(false);
4921
4922 // Send a key. The ANR timer should start because there is no focused window.
4923 // 'focusedApplication' will get blamed if this timer completes.
4924 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004925 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004926 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004927 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4928 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004930
4931 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4932 // then the injected touches won't cause the focused event to get dropped.
4933 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4934 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4935 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4936 // For this test, it means that the key would get delivered to the window once it becomes
4937 // focused.
4938 std::this_thread::sleep_for(10ms);
4939
4940 // Touch unfocused window. This should force the pending key to get dropped.
4941 NotifyMotionArgs motionArgs =
4942 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4943 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4944 mDispatcher->notifyMotion(&motionArgs);
4945
4946 // We do not consume the motion right away, because that would require dispatcher to first
4947 // process (== drop) the key event, and by that time, ANR will be raised.
4948 // Set the focused window first.
4949 mFocusedWindow->setFocusable(true);
4950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4951 setFocusedWindow(mFocusedWindow);
4952 mFocusedWindow->consumeFocusEvent(true);
4953 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4954 // to another application. This could be a bug / behaviour in the policy.
4955
4956 mUnfocusedWindow->consumeMotionDown();
4957
4958 ASSERT_TRUE(mDispatcher->waitForIdle());
4959 // Should not ANR because we actually have a focused window. It was just added too slowly.
4960 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4961}
4962
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004963// These tests ensure we cannot send touch events to a window that's positioned behind a window
4964// that has feature NO_INPUT_CHANNEL.
4965// Layout:
4966// Top (closest to user)
4967// mNoInputWindow (above all windows)
4968// mBottomWindow
4969// Bottom (furthest from user)
4970class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4971 virtual void SetUp() override {
4972 InputDispatcherTest::SetUp();
4973
4974 mApplication = std::make_shared<FakeApplicationHandle>();
4975 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4976 "Window without input channel", ADISPLAY_ID_DEFAULT,
4977 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4978
chaviw3277faf2021-05-19 16:45:23 -05004979 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004980 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4981 // It's perfectly valid for this window to not have an associated input channel
4982
4983 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4984 ADISPLAY_ID_DEFAULT);
4985 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4986
4987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4988 }
4989
4990protected:
4991 std::shared_ptr<FakeApplicationHandle> mApplication;
4992 sp<FakeWindowHandle> mNoInputWindow;
4993 sp<FakeWindowHandle> mBottomWindow;
4994};
4995
4996TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4997 PointF touchedPoint = {10, 10};
4998
4999 NotifyMotionArgs motionArgs =
5000 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5001 ADISPLAY_ID_DEFAULT, {touchedPoint});
5002 mDispatcher->notifyMotion(&motionArgs);
5003
5004 mNoInputWindow->assertNoEvents();
5005 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5006 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5007 // and therefore should prevent mBottomWindow from receiving touches
5008 mBottomWindow->assertNoEvents();
5009}
5010
5011/**
5012 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5013 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5014 */
5015TEST_F(InputDispatcherMultiWindowOcclusionTests,
5016 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5017 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5018 "Window with input channel and NO_INPUT_CHANNEL",
5019 ADISPLAY_ID_DEFAULT);
5020
chaviw3277faf2021-05-19 16:45:23 -05005021 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005022 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5024
5025 PointF touchedPoint = {10, 10};
5026
5027 NotifyMotionArgs motionArgs =
5028 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5029 ADISPLAY_ID_DEFAULT, {touchedPoint});
5030 mDispatcher->notifyMotion(&motionArgs);
5031
5032 mNoInputWindow->assertNoEvents();
5033 mBottomWindow->assertNoEvents();
5034}
5035
Vishnu Nair958da932020-08-21 17:12:37 -07005036class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5037protected:
5038 std::shared_ptr<FakeApplicationHandle> mApp;
5039 sp<FakeWindowHandle> mWindow;
5040 sp<FakeWindowHandle> mMirror;
5041
5042 virtual void SetUp() override {
5043 InputDispatcherTest::SetUp();
5044 mApp = std::make_shared<FakeApplicationHandle>();
5045 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5046 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5047 mWindow->getToken());
5048 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5049 mWindow->setFocusable(true);
5050 mMirror->setFocusable(true);
5051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5052 }
5053};
5054
5055TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5056 // Request focus on a mirrored window
5057 setFocusedWindow(mMirror);
5058
5059 // window gets focused
5060 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5062 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005063 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5064}
5065
5066// A focused & mirrored window remains focused only if the window and its mirror are both
5067// focusable.
5068TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5069 setFocusedWindow(mMirror);
5070
5071 // window gets focused
5072 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5074 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005075 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5077 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005078 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5079
5080 mMirror->setFocusable(false);
5081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5082
5083 // window loses focus since one of the windows associated with the token in not focusable
5084 mWindow->consumeFocusEvent(false);
5085
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005086 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5087 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005088 mWindow->assertNoEvents();
5089}
5090
5091// A focused & mirrored window remains focused until the window and its mirror both become
5092// invisible.
5093TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5094 setFocusedWindow(mMirror);
5095
5096 // window gets focused
5097 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5099 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005100 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5102 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005103 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5104
5105 mMirror->setVisible(false);
5106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5107
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5109 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005110 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5112 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005113 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5114
5115 mWindow->setVisible(false);
5116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5117
5118 // window loses focus only after all windows associated with the token become invisible.
5119 mWindow->consumeFocusEvent(false);
5120
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005121 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5122 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005123 mWindow->assertNoEvents();
5124}
5125
5126// A focused & mirrored window remains focused until both windows are removed.
5127TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5128 setFocusedWindow(mMirror);
5129
5130 // window gets focused
5131 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5133 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005134 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5136 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005137 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5138
5139 // single window is removed but the window token remains focused
5140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5141
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5143 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005144 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005145 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5146 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005147 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5148
5149 // Both windows are removed
5150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5151 mWindow->consumeFocusEvent(false);
5152
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005153 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5154 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005155 mWindow->assertNoEvents();
5156}
5157
5158// Focus request can be pending until one window becomes visible.
5159TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5160 // Request focus on an invisible mirror.
5161 mWindow->setVisible(false);
5162 mMirror->setVisible(false);
5163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5164 setFocusedWindow(mMirror);
5165
5166 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005168 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005169 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005170
5171 mMirror->setVisible(true);
5172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5173
5174 // window gets focused
5175 mWindow->consumeFocusEvent(true);
5176 // window gets the pending key event
5177 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5178}
Prabir Pradhan99987712020-11-10 18:43:05 -08005179
5180class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5181protected:
5182 std::shared_ptr<FakeApplicationHandle> mApp;
5183 sp<FakeWindowHandle> mWindow;
5184 sp<FakeWindowHandle> mSecondWindow;
5185
5186 void SetUp() override {
5187 InputDispatcherTest::SetUp();
5188 mApp = std::make_shared<FakeApplicationHandle>();
5189 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5190 mWindow->setFocusable(true);
5191 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5192 mSecondWindow->setFocusable(true);
5193
5194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5196
5197 setFocusedWindow(mWindow);
5198 mWindow->consumeFocusEvent(true);
5199 }
5200
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005201 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5202 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005203 mDispatcher->notifyPointerCaptureChanged(&args);
5204 }
5205
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005206 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5207 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005208 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005209 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5210 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005211 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005212 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005213 }
5214};
5215
5216TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5217 // Ensure that capture cannot be obtained for unfocused windows.
5218 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5219 mFakePolicy->assertSetPointerCaptureNotCalled();
5220 mSecondWindow->assertNoEvents();
5221
5222 // Ensure that capture can be enabled from the focus window.
5223 requestAndVerifyPointerCapture(mWindow, true);
5224
5225 // Ensure that capture cannot be disabled from a window that does not have capture.
5226 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5227 mFakePolicy->assertSetPointerCaptureNotCalled();
5228
5229 // Ensure that capture can be disabled from the window with capture.
5230 requestAndVerifyPointerCapture(mWindow, false);
5231}
5232
5233TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005234 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005235
5236 setFocusedWindow(mSecondWindow);
5237
5238 // Ensure that the capture disabled event was sent first.
5239 mWindow->consumeCaptureEvent(false);
5240 mWindow->consumeFocusEvent(false);
5241 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005242 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005243
5244 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005245 notifyPointerCaptureChanged({});
5246 notifyPointerCaptureChanged(request);
5247 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005248 mWindow->assertNoEvents();
5249 mSecondWindow->assertNoEvents();
5250 mFakePolicy->assertSetPointerCaptureNotCalled();
5251}
5252
5253TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005254 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005255
5256 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005257 notifyPointerCaptureChanged({});
5258 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005259
5260 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005261 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005262 mWindow->consumeCaptureEvent(false);
5263 mWindow->assertNoEvents();
5264}
5265
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005266TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5267 requestAndVerifyPointerCapture(mWindow, true);
5268
5269 // The first window loses focus.
5270 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005271 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005272 mWindow->consumeCaptureEvent(false);
5273
5274 // Request Pointer Capture from the second window before the notification from InputReader
5275 // arrives.
5276 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005277 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005278
5279 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005280 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005281
5282 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005283 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005284
5285 mSecondWindow->consumeFocusEvent(true);
5286 mSecondWindow->consumeCaptureEvent(true);
5287}
5288
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005289TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5290 // App repeatedly enables and disables capture.
5291 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5292 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5293 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5294 mFakePolicy->assertSetPointerCaptureCalled(false);
5295 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5296 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5297
5298 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5299 // first request is now stale, this should do nothing.
5300 notifyPointerCaptureChanged(firstRequest);
5301 mWindow->assertNoEvents();
5302
5303 // InputReader notifies that the second request was enabled.
5304 notifyPointerCaptureChanged(secondRequest);
5305 mWindow->consumeCaptureEvent(true);
5306}
5307
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005308class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5309protected:
5310 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005311
5312 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5313 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5314
5315 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5316 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5317
5318 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5319 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5320 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5321 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5322 MAXIMUM_OBSCURING_OPACITY);
5323
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005324 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005325 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005326 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005327
5328 sp<FakeWindowHandle> mTouchWindow;
5329
5330 virtual void SetUp() override {
5331 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005332 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005333 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5334 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5335 }
5336
5337 virtual void TearDown() override {
5338 InputDispatcherTest::TearDown();
5339 mTouchWindow.clear();
5340 }
5341
chaviw3277faf2021-05-19 16:45:23 -05005342 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5343 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005344 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005345 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005346 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005347 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005348 return window;
5349 }
5350
5351 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5352 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5353 sp<FakeWindowHandle> window =
5354 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5355 // Generate an arbitrary PID based on the UID
5356 window->setOwnerInfo(1777 + (uid % 10000), uid);
5357 return window;
5358 }
5359
5360 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5361 NotifyMotionArgs args =
5362 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5363 ADISPLAY_ID_DEFAULT, points);
5364 mDispatcher->notifyMotion(&args);
5365 }
5366};
5367
5368TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005369 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005370 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005372
5373 touch();
5374
5375 mTouchWindow->assertNoEvents();
5376}
5377
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005378TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005379 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5380 const sp<FakeWindowHandle>& w =
5381 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5383
5384 touch();
5385
5386 mTouchWindow->assertNoEvents();
5387}
5388
5389TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005390 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5391 const sp<FakeWindowHandle>& w =
5392 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5394
5395 touch();
5396
5397 w->assertNoEvents();
5398}
5399
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005400TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005401 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005403
5404 touch();
5405
5406 mTouchWindow->consumeAnyMotionDown();
5407}
5408
5409TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005410 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005411 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005412 w->setFrame(Rect(0, 0, 50, 50));
5413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005414
5415 touch({PointF{100, 100}});
5416
5417 mTouchWindow->consumeAnyMotionDown();
5418}
5419
5420TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005421 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005422 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5424
5425 touch();
5426
5427 mTouchWindow->consumeAnyMotionDown();
5428}
5429
5430TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5431 const sp<FakeWindowHandle>& w =
5432 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005434
5435 touch();
5436
5437 mTouchWindow->consumeAnyMotionDown();
5438}
5439
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005440TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5441 const sp<FakeWindowHandle>& w =
5442 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5444
5445 touch();
5446
5447 w->assertNoEvents();
5448}
5449
5450/**
5451 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5452 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5453 * window, the occluding window will still receive ACTION_OUTSIDE event.
5454 */
5455TEST_F(InputDispatcherUntrustedTouchesTest,
5456 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
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 w->consumeMotionOutside();
5465}
5466
5467TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5468 const sp<FakeWindowHandle>& w =
5469 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005470 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5472
5473 touch();
5474
5475 InputEvent* event = w->consume();
5476 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5477 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5478 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5479 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5480}
5481
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005482TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005483 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005484 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5485 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5487
5488 touch();
5489
5490 mTouchWindow->consumeAnyMotionDown();
5491}
5492
5493TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5494 const sp<FakeWindowHandle>& w =
5495 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5496 MAXIMUM_OBSCURING_OPACITY);
5497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005498
5499 touch();
5500
5501 mTouchWindow->consumeAnyMotionDown();
5502}
5503
5504TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005505 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005506 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5507 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5509
5510 touch();
5511
5512 mTouchWindow->assertNoEvents();
5513}
5514
5515TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5516 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5517 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005518 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5519 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005520 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005521 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5522 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5524
5525 touch();
5526
5527 mTouchWindow->assertNoEvents();
5528}
5529
5530TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5531 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5532 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005533 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5534 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005535 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005536 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5537 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5539
5540 touch();
5541
5542 mTouchWindow->consumeAnyMotionDown();
5543}
5544
5545TEST_F(InputDispatcherUntrustedTouchesTest,
5546 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5547 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005548 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5549 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005550 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005551 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5552 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5554
5555 touch();
5556
5557 mTouchWindow->consumeAnyMotionDown();
5558}
5559
5560TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5561 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005562 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5563 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005564 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005565 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5566 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005568
5569 touch();
5570
5571 mTouchWindow->assertNoEvents();
5572}
5573
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005574TEST_F(InputDispatcherUntrustedTouchesTest,
5575 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5576 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005577 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5578 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005579 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005580 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5581 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5583
5584 touch();
5585
5586 mTouchWindow->assertNoEvents();
5587}
5588
5589TEST_F(InputDispatcherUntrustedTouchesTest,
5590 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5591 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005592 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5593 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005594 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005595 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5596 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5598
5599 touch();
5600
5601 mTouchWindow->consumeAnyMotionDown();
5602}
5603
5604TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5605 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005606 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5607 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5609
5610 touch();
5611
5612 mTouchWindow->consumeAnyMotionDown();
5613}
5614
5615TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5616 const sp<FakeWindowHandle>& w =
5617 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5618 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5619
5620 touch();
5621
5622 mTouchWindow->consumeAnyMotionDown();
5623}
5624
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005625TEST_F(InputDispatcherUntrustedTouchesTest,
5626 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5627 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5628 const sp<FakeWindowHandle>& w =
5629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5631
5632 touch();
5633
5634 mTouchWindow->assertNoEvents();
5635}
5636
5637TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5638 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5639 const sp<FakeWindowHandle>& w =
5640 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5641 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5642
5643 touch();
5644
5645 mTouchWindow->consumeAnyMotionDown();
5646}
5647
5648TEST_F(InputDispatcherUntrustedTouchesTest,
5649 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5650 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5651 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005652 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5653 OPACITY_ABOVE_THRESHOLD);
5654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5655
5656 touch();
5657
5658 mTouchWindow->consumeAnyMotionDown();
5659}
5660
5661TEST_F(InputDispatcherUntrustedTouchesTest,
5662 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5663 const sp<FakeWindowHandle>& w1 =
5664 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5665 OPACITY_BELOW_THRESHOLD);
5666 const sp<FakeWindowHandle>& w2 =
5667 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5668 OPACITY_BELOW_THRESHOLD);
5669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5670
5671 touch();
5672
5673 mTouchWindow->assertNoEvents();
5674}
5675
5676/**
5677 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5678 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5679 * (which alone would result in allowing touches) does not affect the blocking behavior.
5680 */
5681TEST_F(InputDispatcherUntrustedTouchesTest,
5682 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5683 const sp<FakeWindowHandle>& wB =
5684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5685 OPACITY_BELOW_THRESHOLD);
5686 const sp<FakeWindowHandle>& wC =
5687 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5688 OPACITY_BELOW_THRESHOLD);
5689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5690
5691 touch();
5692
5693 mTouchWindow->assertNoEvents();
5694}
5695
5696/**
5697 * This test is testing that a window from a different UID but with same application token doesn't
5698 * block the touch. Apps can share the application token for close UI collaboration for example.
5699 */
5700TEST_F(InputDispatcherUntrustedTouchesTest,
5701 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5702 const sp<FakeWindowHandle>& w =
5703 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5704 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5706
5707 touch();
5708
5709 mTouchWindow->consumeAnyMotionDown();
5710}
5711
arthurhungb89ccb02020-12-30 16:19:01 +08005712class InputDispatcherDragTests : public InputDispatcherTest {
5713protected:
5714 std::shared_ptr<FakeApplicationHandle> mApp;
5715 sp<FakeWindowHandle> mWindow;
5716 sp<FakeWindowHandle> mSecondWindow;
5717 sp<FakeWindowHandle> mDragWindow;
5718
5719 void SetUp() override {
5720 InputDispatcherTest::SetUp();
5721 mApp = std::make_shared<FakeApplicationHandle>();
5722 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5723 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005724 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005725
5726 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5727 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005728 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005729
5730 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5732 }
5733
5734 // Start performing drag, we will create a drag window and transfer touch to it.
5735 void performDrag() {
5736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5738 {50, 50}))
5739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5740
5741 // Window should receive motion event.
5742 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5743
5744 // The drag window covers the entire display
5745 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5746 mDispatcher->setInputWindows(
5747 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5748
5749 // Transfer touch focus to the drag window
5750 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5751 true /* isDragDrop */);
5752 mWindow->consumeMotionCancel();
5753 mDragWindow->consumeMotionDown();
5754 }
arthurhung6d4bed92021-03-17 11:59:33 +08005755
5756 // Start performing drag, we will create a drag window and transfer touch to it.
5757 void performStylusDrag() {
5758 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5759 injectMotionEvent(mDispatcher,
5760 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5761 AINPUT_SOURCE_STYLUS)
5762 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5763 .pointer(PointerBuilder(0,
5764 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5765 .x(50)
5766 .y(50))
5767 .build()));
5768 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5769
5770 // The drag window covers the entire display
5771 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5772 mDispatcher->setInputWindows(
5773 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5774
5775 // Transfer touch focus to the drag window
5776 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5777 true /* isDragDrop */);
5778 mWindow->consumeMotionCancel();
5779 mDragWindow->consumeMotionDown();
5780 }
arthurhungb89ccb02020-12-30 16:19:01 +08005781};
5782
5783TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5784 performDrag();
5785
5786 // Move on window.
5787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5788 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5789 ADISPLAY_ID_DEFAULT, {50, 50}))
5790 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5791 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5792 mWindow->consumeDragEvent(false, 50, 50);
5793 mSecondWindow->assertNoEvents();
5794
5795 // Move to another window.
5796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5797 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5798 ADISPLAY_ID_DEFAULT, {150, 50}))
5799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5800 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5801 mWindow->consumeDragEvent(true, 150, 50);
5802 mSecondWindow->consumeDragEvent(false, 50, 50);
5803
5804 // Move back to original window.
5805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5806 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5807 ADISPLAY_ID_DEFAULT, {50, 50}))
5808 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5809 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5810 mWindow->consumeDragEvent(false, 50, 50);
5811 mSecondWindow->consumeDragEvent(true, -50, 50);
5812
5813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5814 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5815 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5816 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5817 mWindow->assertNoEvents();
5818 mSecondWindow->assertNoEvents();
5819}
5820
arthurhungf452d0b2021-01-06 00:19:52 +08005821TEST_F(InputDispatcherDragTests, DragAndDrop) {
5822 performDrag();
5823
5824 // Move on window.
5825 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5826 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5827 ADISPLAY_ID_DEFAULT, {50, 50}))
5828 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5829 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5830 mWindow->consumeDragEvent(false, 50, 50);
5831 mSecondWindow->assertNoEvents();
5832
5833 // Move to another window.
5834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5835 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5836 ADISPLAY_ID_DEFAULT, {150, 50}))
5837 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5838 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5839 mWindow->consumeDragEvent(true, 150, 50);
5840 mSecondWindow->consumeDragEvent(false, 50, 50);
5841
5842 // drop to another window.
5843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5844 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5845 {150, 50}))
5846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5847 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5848 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5849 mWindow->assertNoEvents();
5850 mSecondWindow->assertNoEvents();
5851}
5852
arthurhung6d4bed92021-03-17 11:59:33 +08005853TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5854 performStylusDrag();
5855
5856 // Move on window and keep button pressed.
5857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5858 injectMotionEvent(mDispatcher,
5859 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5860 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5861 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5862 .x(50)
5863 .y(50))
5864 .build()))
5865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5866 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5867 mWindow->consumeDragEvent(false, 50, 50);
5868 mSecondWindow->assertNoEvents();
5869
5870 // Move to another window and release button, expect to drop item.
5871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5872 injectMotionEvent(mDispatcher,
5873 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5874 .buttonState(0)
5875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5876 .x(150)
5877 .y(50))
5878 .build()))
5879 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5880 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5881 mWindow->assertNoEvents();
5882 mSecondWindow->assertNoEvents();
5883 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5884
5885 // nothing to the window.
5886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5887 injectMotionEvent(mDispatcher,
5888 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5889 .buttonState(0)
5890 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5891 .x(150)
5892 .y(50))
5893 .build()))
5894 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5895 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5896 mWindow->assertNoEvents();
5897 mSecondWindow->assertNoEvents();
5898}
5899
Arthur Hung6d0571e2021-04-09 20:18:16 +08005900TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5901 performDrag();
5902
5903 // Set second window invisible.
5904 mSecondWindow->setVisible(false);
5905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5906
5907 // Move on window.
5908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5909 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5910 ADISPLAY_ID_DEFAULT, {50, 50}))
5911 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5912 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5913 mWindow->consumeDragEvent(false, 50, 50);
5914 mSecondWindow->assertNoEvents();
5915
5916 // Move to another window.
5917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5918 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5919 ADISPLAY_ID_DEFAULT, {150, 50}))
5920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5921 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5922 mWindow->consumeDragEvent(true, 150, 50);
5923 mSecondWindow->assertNoEvents();
5924
5925 // drop to another window.
5926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5927 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5928 {150, 50}))
5929 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5930 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5931 mFakePolicy->assertDropTargetEquals(nullptr);
5932 mWindow->assertNoEvents();
5933 mSecondWindow->assertNoEvents();
5934}
5935
Vishnu Nair062a8672021-09-03 16:07:44 -07005936class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5937
5938TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5939 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5940 sp<FakeWindowHandle> window =
5941 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5942 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5943 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5944 window->setFocusable(true);
5945 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5946 setFocusedWindow(window);
5947 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5948
5949 // With the flag set, window should not get any input
5950 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5951 mDispatcher->notifyKey(&keyArgs);
5952 window->assertNoEvents();
5953
5954 NotifyMotionArgs motionArgs =
5955 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5956 ADISPLAY_ID_DEFAULT);
5957 mDispatcher->notifyMotion(&motionArgs);
5958 window->assertNoEvents();
5959
5960 // With the flag cleared, the window should get input
5961 window->setInputFeatures({});
5962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5963
5964 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5965 mDispatcher->notifyKey(&keyArgs);
5966 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5967
5968 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5969 ADISPLAY_ID_DEFAULT);
5970 mDispatcher->notifyMotion(&motionArgs);
5971 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5972 window->assertNoEvents();
5973}
5974
5975TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5976 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5977 std::make_shared<FakeApplicationHandle>();
5978 sp<FakeWindowHandle> obscuringWindow =
5979 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5980 ADISPLAY_ID_DEFAULT);
5981 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5982 obscuringWindow->setOwnerInfo(111, 111);
5983 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5985 sp<FakeWindowHandle> window =
5986 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5987 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5988 window->setOwnerInfo(222, 222);
5989 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5990 window->setFocusable(true);
5991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5992 setFocusedWindow(window);
5993 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5994
5995 // With the flag set, window should not get any input
5996 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5997 mDispatcher->notifyKey(&keyArgs);
5998 window->assertNoEvents();
5999
6000 NotifyMotionArgs motionArgs =
6001 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6002 ADISPLAY_ID_DEFAULT);
6003 mDispatcher->notifyMotion(&motionArgs);
6004 window->assertNoEvents();
6005
6006 // With the flag cleared, the window should get input
6007 window->setInputFeatures({});
6008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6009
6010 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6011 mDispatcher->notifyKey(&keyArgs);
6012 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6013
6014 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6015 ADISPLAY_ID_DEFAULT);
6016 mDispatcher->notifyMotion(&motionArgs);
6017 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6018 window->assertNoEvents();
6019}
6020
6021TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6022 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6023 std::make_shared<FakeApplicationHandle>();
6024 sp<FakeWindowHandle> obscuringWindow =
6025 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6026 ADISPLAY_ID_DEFAULT);
6027 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6028 obscuringWindow->setOwnerInfo(111, 111);
6029 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6030 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6031 sp<FakeWindowHandle> window =
6032 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6033 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6034 window->setOwnerInfo(222, 222);
6035 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6036 window->setFocusable(true);
6037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6038 setFocusedWindow(window);
6039 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6040
6041 // With the flag set, window should not get any input
6042 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6043 mDispatcher->notifyKey(&keyArgs);
6044 window->assertNoEvents();
6045
6046 NotifyMotionArgs motionArgs =
6047 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6048 ADISPLAY_ID_DEFAULT);
6049 mDispatcher->notifyMotion(&motionArgs);
6050 window->assertNoEvents();
6051
6052 // When the window is no longer obscured because it went on top, it should get input
6053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6054
6055 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6056 mDispatcher->notifyKey(&keyArgs);
6057 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6058
6059 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6060 ADISPLAY_ID_DEFAULT);
6061 mDispatcher->notifyMotion(&motionArgs);
6062 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6063 window->assertNoEvents();
6064}
6065
Antonio Kantekf16f2832021-09-28 04:39:20 +00006066class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6067protected:
6068 std::shared_ptr<FakeApplicationHandle> mApp;
6069 sp<FakeWindowHandle> mWindow;
6070 sp<FakeWindowHandle> mSecondWindow;
6071
6072 void SetUp() override {
6073 InputDispatcherTest::SetUp();
6074
6075 mApp = std::make_shared<FakeApplicationHandle>();
6076 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6077 mWindow->setFocusable(true);
6078 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6079 mSecondWindow->setFocusable(true);
6080
6081 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6083
6084 setFocusedWindow(mWindow);
6085 mWindow->consumeFocusEvent(true);
6086 }
6087
6088 void changeAndVerifyTouchMode(bool inTouchMode) {
6089 mDispatcher->setInTouchMode(inTouchMode);
6090 mWindow->consumeTouchModeEvent(inTouchMode);
6091 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6092 }
6093};
6094
6095TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6096 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6097}
6098
6099TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6100 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6101 mWindow->assertNoEvents();
6102 mSecondWindow->assertNoEvents();
6103}
6104
Garfield Tane84e6f92019-08-29 17:28:41 -07006105} // namespace android::inputdispatcher