blob: 515a01e13775db5f3e76006e9f5c46372f52db68 [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());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100845 }
846
Prabir Pradhan99987712020-11-10 18:43:05 -0800847 void consumeCaptureEvent(bool hasCapture) {
848 const InputEvent* event = consume();
849 ASSERT_NE(nullptr, event) << mName.c_str()
850 << ": consumer should have returned non-NULL event.";
851 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
852 << "Got " << inputEventTypeToString(event->getType())
853 << " event instead of CAPTURE event";
854
855 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
856 << mName.c_str() << ": event displayId should always be NONE.";
857
858 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
859 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
860 }
861
arthurhungb89ccb02020-12-30 16:19:01 +0800862 void consumeDragEvent(bool isExiting, float x, float y) {
863 const InputEvent* event = consume();
864 ASSERT_NE(nullptr, event) << mName.c_str()
865 << ": consumer should have returned non-NULL event.";
866 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
867 << "Got " << inputEventTypeToString(event->getType())
868 << " event instead of DRAG event";
869
870 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
871 << mName.c_str() << ": event displayId should always be NONE.";
872
873 const auto& dragEvent = static_cast<const DragEvent&>(*event);
874 EXPECT_EQ(isExiting, dragEvent.isExiting());
875 EXPECT_EQ(x, dragEvent.getX());
876 EXPECT_EQ(y, dragEvent.getY());
877 }
878
Antonio Kantekf16f2832021-09-28 04:39:20 +0000879 void consumeTouchModeEvent(bool inTouchMode) {
880 const InputEvent* event = consume();
881 ASSERT_NE(nullptr, event) << mName.c_str()
882 << ": consumer should have returned non-NULL event.";
883 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
884 << "Got " << inputEventTypeToString(event->getType())
885 << " event instead of TOUCH_MODE event";
886
887 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
888 << mName.c_str() << ": event displayId should always be NONE.";
889 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
890 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
891 }
892
chaviwd1c23182019-12-20 18:44:56 -0800893 void assertNoEvents() {
894 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700895 if (event == nullptr) {
896 return;
897 }
898 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
899 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
900 ADD_FAILURE() << "Received key event "
901 << KeyEvent::actionToString(keyEvent.getAction());
902 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
903 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
904 ADD_FAILURE() << "Received motion event "
905 << MotionEvent::actionToString(motionEvent.getAction());
906 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
907 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
908 ADD_FAILURE() << "Received focus event, hasFocus = "
909 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800910 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
911 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
912 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
913 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000914 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
915 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
916 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
917 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918 }
919 FAIL() << mName.c_str()
920 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800921 }
922
923 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
924
925protected:
926 std::unique_ptr<InputConsumer> mConsumer;
927 PreallocatedInputEventFactory mEventFactory;
928
929 std::string mName;
930};
931
chaviw3277faf2021-05-19 16:45:23 -0500932class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800933public:
934 static const int32_t WIDTH = 600;
935 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800936
Chris Yea209fde2020-07-22 13:54:51 -0700937 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700938 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500939 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800940 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500941 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700942 base::Result<std::unique_ptr<InputChannel>> channel =
943 dispatcher->createInputChannel(name);
944 token = (*channel)->getConnectionToken();
945 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800946 }
947
948 inputApplicationHandle->updateInfo();
949 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
950
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500951 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700952 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800953 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500954 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500955 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000956 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800957 mInfo.frameLeft = 0;
958 mInfo.frameTop = 0;
959 mInfo.frameRight = WIDTH;
960 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700961 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800962 mInfo.globalScaleFactor = 1.0;
963 mInfo.touchableRegion.clear();
964 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
965 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700966 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800967 mInfo.hasWallpaper = false;
968 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800969 mInfo.ownerPid = INJECTOR_PID;
970 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800971 mInfo.displayId = displayId;
972 }
973
Arthur Hungabbb9d82021-09-01 14:52:30 +0000974 sp<FakeWindowHandle> clone(
975 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700976 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +0000977 sp<FakeWindowHandle> handle =
978 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
979 displayId, mInfo.token);
980 return handle;
981 }
982
Vishnu Nair47074b82020-08-14 11:54:47 -0700983 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800984
Vishnu Nair958da932020-08-21 17:12:37 -0700985 void setVisible(bool visible) { mInfo.visible = visible; }
986
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700987 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500988 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700989 }
990
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700991 void setPaused(bool paused) { mInfo.paused = paused; }
992
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000993 void setAlpha(float alpha) { mInfo.alpha = alpha; }
994
chaviw3277faf2021-05-19 16:45:23 -0500995 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000996
Bernardo Rufino7393d172021-02-26 13:56:11 +0000997 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
998
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -0700999 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001000 mInfo.frameLeft = frame.left;
1001 mInfo.frameTop = frame.top;
1002 mInfo.frameRight = frame.right;
1003 mInfo.frameBottom = frame.bottom;
1004 mInfo.touchableRegion.clear();
1005 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001006
1007 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1008 ui::Transform translate;
1009 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1010 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001011 }
1012
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001013 void setType(WindowInfo::Type type) { mInfo.type = type; }
1014
1015 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1016
chaviw3277faf2021-05-19 16:45:23 -05001017 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001018
chaviw3277faf2021-05-19 16:45:23 -05001019 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001020
chaviw3277faf2021-05-19 16:45:23 -05001021 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001022
chaviw9eaa22c2020-07-01 16:21:27 -07001023 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1024 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1025 }
1026
1027 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001028
yunho.shinf4a80b82020-11-16 21:13:57 +09001029 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1030
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001031 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1032 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1033 expectedFlags);
1034 }
1035
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001036 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1037 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1038 }
1039
Svet Ganov5d3bc372020-01-26 23:11:07 -08001040 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001041 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001042 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1043 expectedFlags);
1044 }
1045
1046 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001047 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001048 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1049 expectedFlags);
1050 }
1051
1052 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001053 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001054 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1055 }
1056
1057 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1058 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001059 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1060 expectedFlags);
1061 }
1062
Svet Ganov5d3bc372020-01-26 23:11:07 -08001063 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001064 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1065 int32_t expectedFlags = 0) {
1066 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1067 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001068 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1069 }
1070
1071 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001072 int32_t expectedFlags = 0) {
1073 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1074 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001075 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1076 }
1077
1078 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001079 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001080 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1081 expectedFlags);
1082 }
1083
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001084 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1085 int32_t expectedFlags = 0) {
1086 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1087 expectedFlags);
1088 }
1089
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001090 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1091 ASSERT_NE(mInputReceiver, nullptr)
1092 << "Cannot consume events from a window with no receiver";
1093 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1094 }
1095
Prabir Pradhan99987712020-11-10 18:43:05 -08001096 void consumeCaptureEvent(bool hasCapture) {
1097 ASSERT_NE(mInputReceiver, nullptr)
1098 << "Cannot consume events from a window with no receiver";
1099 mInputReceiver->consumeCaptureEvent(hasCapture);
1100 }
1101
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001102 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1103 std::optional<int32_t> expectedDisplayId,
1104 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001105 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1106 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1107 expectedFlags);
1108 }
1109
arthurhungb89ccb02020-12-30 16:19:01 +08001110 void consumeDragEvent(bool isExiting, float x, float y) {
1111 mInputReceiver->consumeDragEvent(isExiting, x, y);
1112 }
1113
Antonio Kantekf16f2832021-09-28 04:39:20 +00001114 void consumeTouchModeEvent(bool inTouchMode) {
1115 ASSERT_NE(mInputReceiver, nullptr)
1116 << "Cannot consume events from a window with no receiver";
1117 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1118 }
1119
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001120 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001121 if (mInputReceiver == nullptr) {
1122 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1123 return std::nullopt;
1124 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001125 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001126 }
1127
1128 void finishEvent(uint32_t sequenceNum) {
1129 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1130 mInputReceiver->finishEvent(sequenceNum);
1131 }
1132
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001133 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1134 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1135 mInputReceiver->sendTimeline(inputEventId, timeline);
1136 }
1137
chaviwaf87b3e2019-10-01 16:59:28 -07001138 InputEvent* consume() {
1139 if (mInputReceiver == nullptr) {
1140 return nullptr;
1141 }
1142 return mInputReceiver->consume();
1143 }
1144
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001145 MotionEvent* consumeMotion() {
1146 InputEvent* event = consume();
1147 if (event == nullptr) {
1148 ADD_FAILURE() << "Consume failed : no event";
1149 return nullptr;
1150 }
1151 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1152 ADD_FAILURE() << "Instead of motion event, got "
1153 << inputEventTypeToString(event->getType());
1154 return nullptr;
1155 }
1156 return static_cast<MotionEvent*>(event);
1157 }
1158
Arthur Hungb92218b2018-08-14 12:00:21 +08001159 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001160 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001161 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001162 return; // Can't receive events if the window does not have input channel
1163 }
1164 ASSERT_NE(nullptr, mInputReceiver)
1165 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001166 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001167 }
1168
chaviwaf87b3e2019-10-01 16:59:28 -07001169 sp<IBinder> getToken() { return mInfo.token; }
1170
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001171 const std::string& getName() { return mName; }
1172
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001173 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1174 mInfo.ownerPid = ownerPid;
1175 mInfo.ownerUid = ownerUid;
1176 }
1177
chaviwd1c23182019-12-20 18:44:56 -08001178private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001179 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001180 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001181 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001182};
1183
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001184std::atomic<int32_t> FakeWindowHandle::sId{1};
1185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001186static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001187 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001188 int32_t displayId = ADISPLAY_ID_NONE,
1189 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001190 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1191 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001192 KeyEvent event;
1193 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1194
1195 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001196 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001197 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1198 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001199
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001200 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1201 if (!allowKeyRepeat) {
1202 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1203 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001204 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001205 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001206 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001207}
1208
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001209static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001210 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001211 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1212}
1213
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001214// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1215// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1216// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001217static InputEventInjectionResult injectKeyDownNoRepeat(
1218 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001219 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1220 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1221 /* allowKeyRepeat */ false);
1222}
1223
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001224static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001225 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1227}
1228
Garfield Tandf26e862020-07-01 20:18:19 -07001229class PointerBuilder {
1230public:
1231 PointerBuilder(int32_t id, int32_t toolType) {
1232 mProperties.clear();
1233 mProperties.id = id;
1234 mProperties.toolType = toolType;
1235 mCoords.clear();
1236 }
1237
1238 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1239
1240 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1241
1242 PointerBuilder& axis(int32_t axis, float value) {
1243 mCoords.setAxisValue(axis, value);
1244 return *this;
1245 }
1246
1247 PointerProperties buildProperties() const { return mProperties; }
1248
1249 PointerCoords buildCoords() const { return mCoords; }
1250
1251private:
1252 PointerProperties mProperties;
1253 PointerCoords mCoords;
1254};
1255
1256class MotionEventBuilder {
1257public:
1258 MotionEventBuilder(int32_t action, int32_t source) {
1259 mAction = action;
1260 mSource = source;
1261 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1262 }
1263
1264 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1265 mEventTime = eventTime;
1266 return *this;
1267 }
1268
1269 MotionEventBuilder& displayId(int32_t displayId) {
1270 mDisplayId = displayId;
1271 return *this;
1272 }
1273
1274 MotionEventBuilder& actionButton(int32_t actionButton) {
1275 mActionButton = actionButton;
1276 return *this;
1277 }
1278
arthurhung6d4bed92021-03-17 11:59:33 +08001279 MotionEventBuilder& buttonState(int32_t buttonState) {
1280 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001281 return *this;
1282 }
1283
1284 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1285 mRawXCursorPosition = rawXCursorPosition;
1286 return *this;
1287 }
1288
1289 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1290 mRawYCursorPosition = rawYCursorPosition;
1291 return *this;
1292 }
1293
1294 MotionEventBuilder& pointer(PointerBuilder pointer) {
1295 mPointers.push_back(pointer);
1296 return *this;
1297 }
1298
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001299 MotionEventBuilder& addFlag(uint32_t flags) {
1300 mFlags |= flags;
1301 return *this;
1302 }
1303
Garfield Tandf26e862020-07-01 20:18:19 -07001304 MotionEvent build() {
1305 std::vector<PointerProperties> pointerProperties;
1306 std::vector<PointerCoords> pointerCoords;
1307 for (const PointerBuilder& pointer : mPointers) {
1308 pointerProperties.push_back(pointer.buildProperties());
1309 pointerCoords.push_back(pointer.buildCoords());
1310 }
1311
1312 // Set mouse cursor position for the most common cases to avoid boilerplate.
1313 if (mSource == AINPUT_SOURCE_MOUSE &&
1314 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1315 mPointers.size() == 1) {
1316 mRawXCursorPosition = pointerCoords[0].getX();
1317 mRawYCursorPosition = pointerCoords[0].getY();
1318 }
1319
1320 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001321 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001322 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001323 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001324 mButtonState, MotionClassification::NONE, identityTransform,
1325 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001326 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1327 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001328
1329 return event;
1330 }
1331
1332private:
1333 int32_t mAction;
1334 int32_t mSource;
1335 nsecs_t mEventTime;
1336 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1337 int32_t mActionButton{0};
1338 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001339 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001340 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1341 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1342
1343 std::vector<PointerBuilder> mPointers;
1344};
1345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001346static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001347 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001348 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001349 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001350 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1351 injectionTimeout,
1352 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1353}
1354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001355static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001356 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1357 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001358 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001359 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1360 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001361 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001362 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001363 MotionEvent event = MotionEventBuilder(action, source)
1364 .displayId(displayId)
1365 .eventTime(eventTime)
1366 .rawXCursorPosition(cursorPosition.x)
1367 .rawYCursorPosition(cursorPosition.y)
1368 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1369 .x(position.x)
1370 .y(position.y))
1371 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001372
1373 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001374 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001375}
1376
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001377static InputEventInjectionResult injectMotionDown(
1378 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1379 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001380 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001381}
1382
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001383static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001384 int32_t source, int32_t displayId,
1385 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001386 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001387}
1388
Jackal Guof9696682018-10-05 12:23:23 +08001389static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1390 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1391 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001392 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1393 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1394 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001395
1396 return args;
1397}
1398
chaviwd1c23182019-12-20 18:44:56 -08001399static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1400 const std::vector<PointF>& points) {
1401 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001402 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1403 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1404 }
1405
chaviwd1c23182019-12-20 18:44:56 -08001406 PointerProperties pointerProperties[pointerCount];
1407 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001408
chaviwd1c23182019-12-20 18:44:56 -08001409 for (size_t i = 0; i < pointerCount; i++) {
1410 pointerProperties[i].clear();
1411 pointerProperties[i].id = i;
1412 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001413
chaviwd1c23182019-12-20 18:44:56 -08001414 pointerCoords[i].clear();
1415 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1416 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1417 }
Jackal Guof9696682018-10-05 12:23:23 +08001418
1419 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1420 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001421 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001422 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1423 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001424 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1425 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001426 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1427 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001428
1429 return args;
1430}
1431
chaviwd1c23182019-12-20 18:44:56 -08001432static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1433 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1434}
1435
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001436static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1437 const PointerCaptureRequest& request) {
1438 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001439}
1440
Arthur Hungb92218b2018-08-14 12:00:21 +08001441TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001442 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001443 sp<FakeWindowHandle> window =
1444 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001445
Arthur Hung72d8dc32020-03-28 00:48:39 +00001446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1448 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001450
1451 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001452 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001453}
1454
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001455TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1456 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1457 sp<FakeWindowHandle> window =
1458 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1459
1460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1461 // Inject a MotionEvent to an unknown display.
1462 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1463 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1465
1466 // Window should receive motion event.
1467 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1468}
1469
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001470/**
1471 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1472 * To ensure that window receives only events that were directly inside of it, add
1473 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1474 * when finding touched windows.
1475 * This test serves as a sanity check for the next test, where setInputWindows is
1476 * called twice.
1477 */
1478TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001479 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001480 sp<FakeWindowHandle> window =
1481 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1482 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001483 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001484
1485 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001487 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1488 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001490
1491 // Window should receive motion event.
1492 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1493}
1494
1495/**
1496 * Calling setInputWindows twice, with the same info, should not cause any issues.
1497 * To ensure that window receives only events that were directly inside of it, add
1498 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1499 * when finding touched windows.
1500 */
1501TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001502 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001503 sp<FakeWindowHandle> window =
1504 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1505 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001506 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001507
1508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001511 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1512 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001514
1515 // Window should receive motion event.
1516 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1517}
1518
Arthur Hungb92218b2018-08-14 12:00:21 +08001519// The foreground window should receive the first touch down event.
1520TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001521 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001522 sp<FakeWindowHandle> windowTop =
1523 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1524 sp<FakeWindowHandle> windowSecond =
1525 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001526
Arthur Hung72d8dc32020-03-28 00:48:39 +00001527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1529 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1530 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001531
1532 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001533 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001534 windowSecond->assertNoEvents();
1535}
1536
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001537/**
1538 * Two windows: A top window, and a wallpaper behind the window.
1539 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1540 * gets ACTION_CANCEL.
1541 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1542 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1543 */
1544TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1545 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1546 sp<FakeWindowHandle> foregroundWindow =
1547 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1548 foregroundWindow->setHasWallpaper(true);
1549 sp<FakeWindowHandle> wallpaperWindow =
1550 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1551 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1552 constexpr int expectedWallpaperFlags =
1553 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1554
1555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1558 {100, 200}))
1559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1560
1561 // Both foreground window and its wallpaper should receive the touch down
1562 foregroundWindow->consumeMotionDown();
1563 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1564
1565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1566 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1567 ADISPLAY_ID_DEFAULT, {110, 200}))
1568 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1569
1570 foregroundWindow->consumeMotionMove();
1571 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1572
1573 // Now the foreground window goes away, but the wallpaper stays
1574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1575 foregroundWindow->consumeMotionCancel();
1576 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1577 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1578}
1579
1580/**
1581 * A single window that receives touch (on top), and a wallpaper window underneath it.
1582 * The top window gets a multitouch gesture.
1583 * Ensure that wallpaper gets the same gesture.
1584 */
1585TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1587 sp<FakeWindowHandle> window =
1588 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1589 window->setHasWallpaper(true);
1590
1591 sp<FakeWindowHandle> wallpaperWindow =
1592 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1593 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1594 constexpr int expectedWallpaperFlags =
1595 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1596
1597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1598
1599 // Touch down on top window
1600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1602 {100, 100}))
1603 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1604
1605 // Both top window and its wallpaper should receive the touch down
1606 window->consumeMotionDown();
1607 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1608
1609 // Second finger down on the top window
1610 const MotionEvent secondFingerDownEvent =
1611 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1612 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1613 AINPUT_SOURCE_TOUCHSCREEN)
1614 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1615 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1616 .x(100)
1617 .y(100))
1618 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1619 .x(150)
1620 .y(150))
1621 .build();
1622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1623 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1624 InputEventInjectionSync::WAIT_FOR_RESULT))
1625 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1626
1627 window->consumeMotionPointerDown(1 /* pointerIndex */);
1628 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1629 expectedWallpaperFlags);
1630 window->assertNoEvents();
1631 wallpaperWindow->assertNoEvents();
1632}
1633
1634/**
1635 * Two windows: a window on the left and window on the right.
1636 * A third window, wallpaper, is behind both windows, and spans both top windows.
1637 * The first touch down goes to the left window. A second pointer touches down on the right window.
1638 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1639 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1640 * ACTION_POINTER_DOWN(1).
1641 */
1642TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1644 sp<FakeWindowHandle> leftWindow =
1645 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1646 leftWindow->setFrame(Rect(0, 0, 200, 200));
1647 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1648 leftWindow->setHasWallpaper(true);
1649
1650 sp<FakeWindowHandle> rightWindow =
1651 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1652 rightWindow->setFrame(Rect(200, 0, 400, 200));
1653 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1654 rightWindow->setHasWallpaper(true);
1655
1656 sp<FakeWindowHandle> wallpaperWindow =
1657 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1658 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1659 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1660 constexpr int expectedWallpaperFlags =
1661 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1662
1663 mDispatcher->setInputWindows(
1664 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1665
1666 // Touch down on left window
1667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1668 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1669 {100, 100}))
1670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1671
1672 // Both foreground window and its wallpaper should receive the touch down
1673 leftWindow->consumeMotionDown();
1674 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1675
1676 // Second finger down on the right window
1677 const MotionEvent secondFingerDownEvent =
1678 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1679 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1680 AINPUT_SOURCE_TOUCHSCREEN)
1681 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1682 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1683 .x(100)
1684 .y(100))
1685 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1686 .x(300)
1687 .y(100))
1688 .build();
1689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1690 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1691 InputEventInjectionSync::WAIT_FOR_RESULT))
1692 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1693
1694 leftWindow->consumeMotionMove();
1695 // Since the touch is split, right window gets ACTION_DOWN
1696 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1697 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1698 expectedWallpaperFlags);
1699
1700 // Now, leftWindow, which received the first finger, disappears.
1701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1702 leftWindow->consumeMotionCancel();
1703 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1704 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1705
1706 // The pointer that's still down on the right window moves, and goes to the right window only.
1707 // As far as the dispatcher's concerned though, both pointers are still present.
1708 const MotionEvent secondFingerMoveEvent =
1709 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1710 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1711 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1712 .x(100)
1713 .y(100))
1714 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1715 .x(310)
1716 .y(110))
1717 .build();
1718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1719 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1720 InputEventInjectionSync::WAIT_FOR_RESULT));
1721 rightWindow->consumeMotionMove();
1722
1723 leftWindow->assertNoEvents();
1724 rightWindow->assertNoEvents();
1725 wallpaperWindow->assertNoEvents();
1726}
1727
Garfield Tandf26e862020-07-01 20:18:19 -07001728TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001729 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001730 sp<FakeWindowHandle> windowLeft =
1731 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1732 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001733 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001734 sp<FakeWindowHandle> windowRight =
1735 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1736 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001737 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001738
1739 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1740
1741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1742
1743 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001744 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001745 injectMotionEvent(mDispatcher,
1746 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1747 AINPUT_SOURCE_MOUSE)
1748 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1749 .x(900)
1750 .y(400))
1751 .build()));
1752 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1753 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1754 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1755 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1756
1757 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001758 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001759 injectMotionEvent(mDispatcher,
1760 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1761 AINPUT_SOURCE_MOUSE)
1762 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1763 .x(300)
1764 .y(400))
1765 .build()));
1766 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1767 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1768 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1769 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1770 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1771 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1772
1773 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001775 injectMotionEvent(mDispatcher,
1776 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1777 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1778 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1779 .x(300)
1780 .y(400))
1781 .build()));
1782 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1783
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001785 injectMotionEvent(mDispatcher,
1786 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1787 AINPUT_SOURCE_MOUSE)
1788 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1789 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1790 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1791 .x(300)
1792 .y(400))
1793 .build()));
1794 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1795 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1796
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001798 injectMotionEvent(mDispatcher,
1799 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1800 AINPUT_SOURCE_MOUSE)
1801 .buttonState(0)
1802 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1803 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1804 .x(300)
1805 .y(400))
1806 .build()));
1807 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1808 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1809
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001811 injectMotionEvent(mDispatcher,
1812 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1813 .buttonState(0)
1814 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1815 .x(300)
1816 .y(400))
1817 .build()));
1818 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1819
1820 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001822 injectMotionEvent(mDispatcher,
1823 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1824 AINPUT_SOURCE_MOUSE)
1825 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1826 .x(900)
1827 .y(400))
1828 .build()));
1829 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1830 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1831 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1832 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1833 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1834 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1835}
1836
1837// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1838// directly in this test.
1839TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001840 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001841 sp<FakeWindowHandle> window =
1842 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1843 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001844 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001845
1846 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1847
1848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1849
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001851 injectMotionEvent(mDispatcher,
1852 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1853 AINPUT_SOURCE_MOUSE)
1854 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1855 .x(300)
1856 .y(400))
1857 .build()));
1858 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1859 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1860
1861 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001863 injectMotionEvent(mDispatcher,
1864 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1865 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1866 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1867 .x(300)
1868 .y(400))
1869 .build()));
1870 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1871
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001873 injectMotionEvent(mDispatcher,
1874 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1875 AINPUT_SOURCE_MOUSE)
1876 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1877 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1878 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1879 .x(300)
1880 .y(400))
1881 .build()));
1882 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1883 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1884
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001886 injectMotionEvent(mDispatcher,
1887 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1888 AINPUT_SOURCE_MOUSE)
1889 .buttonState(0)
1890 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1891 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1892 .x(300)
1893 .y(400))
1894 .build()));
1895 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1896 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1897
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001899 injectMotionEvent(mDispatcher,
1900 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1901 .buttonState(0)
1902 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1903 .x(300)
1904 .y(400))
1905 .build()));
1906 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1907
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001909 injectMotionEvent(mDispatcher,
1910 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1911 AINPUT_SOURCE_MOUSE)
1912 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1913 .x(300)
1914 .y(400))
1915 .build()));
1916 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1917 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1918}
1919
Garfield Tan00f511d2019-06-12 16:55:40 -07001920TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001921 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001922
1923 sp<FakeWindowHandle> windowLeft =
1924 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1925 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001926 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001927 sp<FakeWindowHandle> windowRight =
1928 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1929 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001930 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001931
1932 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1933
Arthur Hung72d8dc32020-03-28 00:48:39 +00001934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001935
1936 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1937 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001939 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001940 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001941 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001942 windowRight->assertNoEvents();
1943}
1944
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001945TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001947 sp<FakeWindowHandle> window =
1948 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001949 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001950
Arthur Hung72d8dc32020-03-28 00:48:39 +00001951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001952 setFocusedWindow(window);
1953
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001954 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001955
1956 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1957 mDispatcher->notifyKey(&keyArgs);
1958
1959 // Window should receive key down event.
1960 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1961
1962 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1963 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001964 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001965 mDispatcher->notifyDeviceReset(&args);
1966 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1967 AKEY_EVENT_FLAG_CANCELED);
1968}
1969
1970TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001971 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001972 sp<FakeWindowHandle> window =
1973 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1974
Arthur Hung72d8dc32020-03-28 00:48:39 +00001975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001976
1977 NotifyMotionArgs motionArgs =
1978 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1979 ADISPLAY_ID_DEFAULT);
1980 mDispatcher->notifyMotion(&motionArgs);
1981
1982 // Window should receive motion down event.
1983 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1984
1985 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1986 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001987 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001988 mDispatcher->notifyDeviceReset(&args);
1989 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1990 0 /*expectedFlags*/);
1991}
1992
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001993/**
1994 * Ensure the correct coordinate spaces are used by InputDispatcher.
1995 *
1996 * InputDispatcher works in the display space, so its coordinate system is relative to the display
1997 * panel. Windows get events in the window space, and get raw coordinates in the logical display
1998 * space.
1999 */
2000class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2001public:
2002 void SetUp() override {
2003 InputDispatcherTest::SetUp();
2004 mDisplayInfos.clear();
2005 mWindowInfos.clear();
2006 }
2007
2008 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2009 gui::DisplayInfo info;
2010 info.displayId = displayId;
2011 info.transform = transform;
2012 mDisplayInfos.push_back(std::move(info));
2013 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2014 }
2015
2016 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2017 mWindowInfos.push_back(*windowHandle->getInfo());
2018 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2019 }
2020
2021 // Set up a test scenario where the display has a scaled projection and there are two windows
2022 // on the display.
2023 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2024 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2025 // respectively.
2026 ui::Transform displayTransform;
2027 displayTransform.set(2, 0, 0, 4);
2028 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2029
2030 std::shared_ptr<FakeApplicationHandle> application =
2031 std::make_shared<FakeApplicationHandle>();
2032
2033 // Add two windows to the display. Their frames are represented in the display space.
2034 sp<FakeWindowHandle> firstWindow =
2035 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2036 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2037 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2038 addWindow(firstWindow);
2039
2040 sp<FakeWindowHandle> secondWindow =
2041 new FakeWindowHandle(application, mDispatcher, "Second Window",
2042 ADISPLAY_ID_DEFAULT);
2043 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2044 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2045 addWindow(secondWindow);
2046 return {std::move(firstWindow), std::move(secondWindow)};
2047 }
2048
2049private:
2050 std::vector<gui::DisplayInfo> mDisplayInfos;
2051 std::vector<gui::WindowInfo> mWindowInfos;
2052};
2053
2054TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2055 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2056 // Send down to the first window. The point is represented in the display space. The point is
2057 // selected so that if the hit test was done with the transform applied to it, then it would
2058 // end up in the incorrect window.
2059 NotifyMotionArgs downMotionArgs =
2060 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2061 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2062 mDispatcher->notifyMotion(&downMotionArgs);
2063
2064 firstWindow->consumeMotionDown();
2065 secondWindow->assertNoEvents();
2066}
2067
2068// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2069// the event should be treated as being in the logical display space.
2070TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2071 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2072 // Send down to the first window. The point is represented in the logical display space. The
2073 // point is selected so that if the hit test was done in logical display space, then it would
2074 // end up in the incorrect window.
2075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2076 PointF{75 * 2, 55 * 4});
2077
2078 firstWindow->consumeMotionDown();
2079 secondWindow->assertNoEvents();
2080}
2081
2082TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2083 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2084
2085 // Send down to the second window.
2086 NotifyMotionArgs downMotionArgs =
2087 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2088 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2089 mDispatcher->notifyMotion(&downMotionArgs);
2090
2091 firstWindow->assertNoEvents();
2092 const MotionEvent* event = secondWindow->consumeMotion();
2093 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2094
2095 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2096 EXPECT_EQ(300, event->getRawX(0));
2097 EXPECT_EQ(880, event->getRawY(0));
2098
2099 // Ensure that the x and y values are in the window's coordinate space.
2100 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2101 // the logical display space. This will be the origin of the window space.
2102 EXPECT_EQ(100, event->getX(0));
2103 EXPECT_EQ(80, event->getY(0));
2104}
2105
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002106using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2107 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002108
2109class TransferTouchFixture : public InputDispatcherTest,
2110 public ::testing::WithParamInterface<TransferFunction> {};
2111
2112TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002113 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002114
2115 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002116 sp<FakeWindowHandle> firstWindow =
2117 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2118 sp<FakeWindowHandle> secondWindow =
2119 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002120
2121 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002123
2124 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002125 NotifyMotionArgs downMotionArgs =
2126 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2127 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002128 mDispatcher->notifyMotion(&downMotionArgs);
2129 // Only the first window should get the down event
2130 firstWindow->consumeMotionDown();
2131 secondWindow->assertNoEvents();
2132
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002133 // Transfer touch to the second window
2134 TransferFunction f = GetParam();
2135 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2136 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002137 // The first window gets cancel and the second gets down
2138 firstWindow->consumeMotionCancel();
2139 secondWindow->consumeMotionDown();
2140
2141 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002142 NotifyMotionArgs upMotionArgs =
2143 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2144 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002145 mDispatcher->notifyMotion(&upMotionArgs);
2146 // The first window gets no events and the second gets up
2147 firstWindow->assertNoEvents();
2148 secondWindow->consumeMotionUp();
2149}
2150
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002151TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002152 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002153
2154 PointF touchPoint = {10, 10};
2155
2156 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002157 sp<FakeWindowHandle> firstWindow =
2158 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2159 sp<FakeWindowHandle> secondWindow =
2160 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002161
2162 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002164
2165 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002166 NotifyMotionArgs downMotionArgs =
2167 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2168 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002169 mDispatcher->notifyMotion(&downMotionArgs);
2170 // Only the first window should get the down event
2171 firstWindow->consumeMotionDown();
2172 secondWindow->assertNoEvents();
2173
2174 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002175 NotifyMotionArgs pointerDownMotionArgs =
2176 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2177 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2178 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2179 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002180 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2181 // Only the first window should get the pointer down event
2182 firstWindow->consumeMotionPointerDown(1);
2183 secondWindow->assertNoEvents();
2184
2185 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002186 TransferFunction f = GetParam();
2187 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2188 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002189 // The first window gets cancel and the second gets down and pointer down
2190 firstWindow->consumeMotionCancel();
2191 secondWindow->consumeMotionDown();
2192 secondWindow->consumeMotionPointerDown(1);
2193
2194 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002195 NotifyMotionArgs pointerUpMotionArgs =
2196 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2197 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2198 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2199 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002200 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2201 // The first window gets nothing and the second gets pointer up
2202 firstWindow->assertNoEvents();
2203 secondWindow->consumeMotionPointerUp(1);
2204
2205 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002206 NotifyMotionArgs upMotionArgs =
2207 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2208 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002209 mDispatcher->notifyMotion(&upMotionArgs);
2210 // The first window gets nothing and the second gets up
2211 firstWindow->assertNoEvents();
2212 secondWindow->consumeMotionUp();
2213}
2214
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002215// For the cases of single pointer touch and two pointers non-split touch, the api's
2216// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2217// for the case where there are multiple pointers split across several windows.
2218INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2219 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002220 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2221 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002222 return dispatcher->transferTouch(destChannelToken);
2223 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002224 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2225 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002226 return dispatcher->transferTouchFocus(from, to,
2227 false /*isDragAndDrop*/);
2228 }));
2229
Svet Ganov5d3bc372020-01-26 23:11:07 -08002230TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002231 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002232
2233 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002234 sp<FakeWindowHandle> firstWindow =
2235 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002236 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002237 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002238
2239 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002240 sp<FakeWindowHandle> secondWindow =
2241 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002242 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002243 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002244
2245 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002246 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002247
2248 PointF pointInFirst = {300, 200};
2249 PointF pointInSecond = {300, 600};
2250
2251 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002252 NotifyMotionArgs firstDownMotionArgs =
2253 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2254 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002255 mDispatcher->notifyMotion(&firstDownMotionArgs);
2256 // Only the first window should get the down event
2257 firstWindow->consumeMotionDown();
2258 secondWindow->assertNoEvents();
2259
2260 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002261 NotifyMotionArgs secondDownMotionArgs =
2262 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2263 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2264 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2265 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266 mDispatcher->notifyMotion(&secondDownMotionArgs);
2267 // The first window gets a move and the second a down
2268 firstWindow->consumeMotionMove();
2269 secondWindow->consumeMotionDown();
2270
2271 // Transfer touch focus to the second window
2272 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2273 // The first window gets cancel and the new gets pointer down (it already saw down)
2274 firstWindow->consumeMotionCancel();
2275 secondWindow->consumeMotionPointerDown(1);
2276
2277 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002278 NotifyMotionArgs pointerUpMotionArgs =
2279 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2280 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2281 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2282 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002283 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2284 // The first window gets nothing and the second gets pointer up
2285 firstWindow->assertNoEvents();
2286 secondWindow->consumeMotionPointerUp(1);
2287
2288 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002289 NotifyMotionArgs upMotionArgs =
2290 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2291 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002292 mDispatcher->notifyMotion(&upMotionArgs);
2293 // The first window gets nothing and the second gets up
2294 firstWindow->assertNoEvents();
2295 secondWindow->consumeMotionUp();
2296}
2297
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002298// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2299// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2300// touch is not supported, so the touch should continue on those windows and the transferred-to
2301// window should get nothing.
2302TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2303 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2304
2305 // Create a non touch modal window that supports split touch
2306 sp<FakeWindowHandle> firstWindow =
2307 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2308 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002309 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002310
2311 // Create a non touch modal window that supports split touch
2312 sp<FakeWindowHandle> secondWindow =
2313 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2314 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002315 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002316
2317 // Add the windows to the dispatcher
2318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2319
2320 PointF pointInFirst = {300, 200};
2321 PointF pointInSecond = {300, 600};
2322
2323 // Send down to the first window
2324 NotifyMotionArgs firstDownMotionArgs =
2325 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2326 ADISPLAY_ID_DEFAULT, {pointInFirst});
2327 mDispatcher->notifyMotion(&firstDownMotionArgs);
2328 // Only the first window should get the down event
2329 firstWindow->consumeMotionDown();
2330 secondWindow->assertNoEvents();
2331
2332 // Send down to the second window
2333 NotifyMotionArgs secondDownMotionArgs =
2334 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2335 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2336 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2337 {pointInFirst, pointInSecond});
2338 mDispatcher->notifyMotion(&secondDownMotionArgs);
2339 // The first window gets a move and the second a down
2340 firstWindow->consumeMotionMove();
2341 secondWindow->consumeMotionDown();
2342
2343 // Transfer touch focus to the second window
2344 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2345 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2346 ASSERT_FALSE(transferred);
2347 firstWindow->assertNoEvents();
2348 secondWindow->assertNoEvents();
2349
2350 // The rest of the dispatch should proceed as normal
2351 // Send pointer up to the second window
2352 NotifyMotionArgs pointerUpMotionArgs =
2353 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2354 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2355 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2356 {pointInFirst, pointInSecond});
2357 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2358 // The first window gets MOVE and the second gets pointer up
2359 firstWindow->consumeMotionMove();
2360 secondWindow->consumeMotionUp();
2361
2362 // Send up event to the first window
2363 NotifyMotionArgs upMotionArgs =
2364 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2365 ADISPLAY_ID_DEFAULT);
2366 mDispatcher->notifyMotion(&upMotionArgs);
2367 // The first window gets nothing and the second gets up
2368 firstWindow->consumeMotionUp();
2369 secondWindow->assertNoEvents();
2370}
2371
Arthur Hungabbb9d82021-09-01 14:52:30 +00002372// This case will create two windows and one mirrored window on the default display and mirror
2373// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2374// the windows info of second display before default display.
2375TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2377 sp<FakeWindowHandle> firstWindowInPrimary =
2378 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2379 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2380 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2381 sp<FakeWindowHandle> secondWindowInPrimary =
2382 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2383 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2384 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2385
2386 sp<FakeWindowHandle> mirrorWindowInPrimary =
2387 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2388 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2389 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2390
2391 sp<FakeWindowHandle> firstWindowInSecondary =
2392 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2393 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2394 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2395
2396 sp<FakeWindowHandle> secondWindowInSecondary =
2397 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2398 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2399 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2400
2401 // Update window info, let it find window handle of second display first.
2402 mDispatcher->setInputWindows(
2403 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2404 {ADISPLAY_ID_DEFAULT,
2405 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2406
2407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2408 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2409 {50, 50}))
2410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2411
2412 // Window should receive motion event.
2413 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2414
2415 // Transfer touch focus
2416 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2417 secondWindowInPrimary->getToken()));
2418 // The first window gets cancel.
2419 firstWindowInPrimary->consumeMotionCancel();
2420 secondWindowInPrimary->consumeMotionDown();
2421
2422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2423 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2424 ADISPLAY_ID_DEFAULT, {150, 50}))
2425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2426 firstWindowInPrimary->assertNoEvents();
2427 secondWindowInPrimary->consumeMotionMove();
2428
2429 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2430 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2431 {150, 50}))
2432 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2433 firstWindowInPrimary->assertNoEvents();
2434 secondWindowInPrimary->consumeMotionUp();
2435}
2436
2437// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2438// 'transferTouch' api.
2439TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2441 sp<FakeWindowHandle> firstWindowInPrimary =
2442 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2443 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2444 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2445 sp<FakeWindowHandle> secondWindowInPrimary =
2446 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2447 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2448 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2449
2450 sp<FakeWindowHandle> mirrorWindowInPrimary =
2451 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2452 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2453 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2454
2455 sp<FakeWindowHandle> firstWindowInSecondary =
2456 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2457 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2458 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2459
2460 sp<FakeWindowHandle> secondWindowInSecondary =
2461 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2462 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2463 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2464
2465 // Update window info, let it find window handle of second display first.
2466 mDispatcher->setInputWindows(
2467 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2468 {ADISPLAY_ID_DEFAULT,
2469 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2470
2471 // Touch on second display.
2472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2475
2476 // Window should receive motion event.
2477 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2478
2479 // Transfer touch focus
2480 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2481
2482 // The first window gets cancel.
2483 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2484 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2485
2486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2487 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2488 SECOND_DISPLAY_ID, {150, 50}))
2489 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2490 firstWindowInPrimary->assertNoEvents();
2491 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2492
2493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2494 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2495 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2496 firstWindowInPrimary->assertNoEvents();
2497 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2498}
2499
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002500TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002501 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002502 sp<FakeWindowHandle> window =
2503 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2504
Vishnu Nair47074b82020-08-14 11:54:47 -07002505 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002507 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002508
2509 window->consumeFocusEvent(true);
2510
2511 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2512 mDispatcher->notifyKey(&keyArgs);
2513
2514 // Window should receive key down event.
2515 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2516}
2517
2518TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002519 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002520 sp<FakeWindowHandle> window =
2521 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2522
Arthur Hung72d8dc32020-03-28 00:48:39 +00002523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002524
2525 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2526 mDispatcher->notifyKey(&keyArgs);
2527 mDispatcher->waitForIdle();
2528
2529 window->assertNoEvents();
2530}
2531
2532// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2533TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002534 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002535 sp<FakeWindowHandle> window =
2536 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2537
Arthur Hung72d8dc32020-03-28 00:48:39 +00002538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002539
2540 // Send key
2541 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2542 mDispatcher->notifyKey(&keyArgs);
2543 // Send motion
2544 NotifyMotionArgs motionArgs =
2545 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2546 ADISPLAY_ID_DEFAULT);
2547 mDispatcher->notifyMotion(&motionArgs);
2548
2549 // Window should receive only the motion event
2550 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2551 window->assertNoEvents(); // Key event or focus event will not be received
2552}
2553
arthurhungea3f4fc2020-12-21 23:18:53 +08002554TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2555 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2556
2557 // Create first non touch modal window that supports split touch
2558 sp<FakeWindowHandle> firstWindow =
2559 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2560 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002561 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002562
2563 // Create second non touch modal window that supports split touch
2564 sp<FakeWindowHandle> secondWindow =
2565 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2566 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002567 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002568
2569 // Add the windows to the dispatcher
2570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2571
2572 PointF pointInFirst = {300, 200};
2573 PointF pointInSecond = {300, 600};
2574
2575 // Send down to the first window
2576 NotifyMotionArgs firstDownMotionArgs =
2577 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2578 ADISPLAY_ID_DEFAULT, {pointInFirst});
2579 mDispatcher->notifyMotion(&firstDownMotionArgs);
2580 // Only the first window should get the down event
2581 firstWindow->consumeMotionDown();
2582 secondWindow->assertNoEvents();
2583
2584 // Send down to the second window
2585 NotifyMotionArgs secondDownMotionArgs =
2586 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2587 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2588 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2589 {pointInFirst, pointInSecond});
2590 mDispatcher->notifyMotion(&secondDownMotionArgs);
2591 // The first window gets a move and the second a down
2592 firstWindow->consumeMotionMove();
2593 secondWindow->consumeMotionDown();
2594
2595 // Send pointer cancel to the second window
2596 NotifyMotionArgs pointerUpMotionArgs =
2597 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2598 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2599 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2600 {pointInFirst, pointInSecond});
2601 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2602 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2603 // The first window gets move and the second gets cancel.
2604 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2605 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2606
2607 // Send up event.
2608 NotifyMotionArgs upMotionArgs =
2609 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2610 ADISPLAY_ID_DEFAULT);
2611 mDispatcher->notifyMotion(&upMotionArgs);
2612 // The first window gets up and the second gets nothing.
2613 firstWindow->consumeMotionUp();
2614 secondWindow->assertNoEvents();
2615}
2616
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002617TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2618 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2619
2620 sp<FakeWindowHandle> window =
2621 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2623 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2624 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2625 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2626
2627 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2628 window->assertNoEvents();
2629 mDispatcher->waitForIdle();
2630}
2631
chaviwd1c23182019-12-20 18:44:56 -08002632class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002633public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002634 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002635 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002636 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002637 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002638 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002639 }
2640
chaviwd1c23182019-12-20 18:44:56 -08002641 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2642
2643 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2644 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2645 expectedDisplayId, expectedFlags);
2646 }
2647
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002648 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2649
2650 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2651
chaviwd1c23182019-12-20 18:44:56 -08002652 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2653 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2654 expectedDisplayId, expectedFlags);
2655 }
2656
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002657 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2658 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2659 expectedDisplayId, expectedFlags);
2660 }
2661
chaviwd1c23182019-12-20 18:44:56 -08002662 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2663 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2664 expectedDisplayId, expectedFlags);
2665 }
2666
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002667 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2668 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2669 expectedDisplayId, expectedFlags);
2670 }
2671
Evan Rosky84f07f02021-04-16 10:42:42 -07002672 MotionEvent* consumeMotion() {
2673 InputEvent* event = mInputReceiver->consume();
2674 if (!event) {
2675 ADD_FAILURE() << "No event was produced";
2676 return nullptr;
2677 }
2678 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2679 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2680 return nullptr;
2681 }
2682 return static_cast<MotionEvent*>(event);
2683 }
2684
chaviwd1c23182019-12-20 18:44:56 -08002685 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2686
2687private:
2688 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002689};
2690
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002691/**
2692 * Two entities that receive touch: A window, and a global monitor.
2693 * The touch goes to the window, and then the window disappears.
2694 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2695 * for the monitor, as well.
2696 * 1. foregroundWindow
2697 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2698 */
2699TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2700 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2701 sp<FakeWindowHandle> window =
2702 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2703
2704 FakeMonitorReceiver monitor =
2705 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2706 false /*isGestureMonitor*/);
2707
2708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2710 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2711 {100, 200}))
2712 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2713
2714 // Both the foreground window and the global monitor should receive the touch down
2715 window->consumeMotionDown();
2716 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2717
2718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2719 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2720 ADISPLAY_ID_DEFAULT, {110, 200}))
2721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2722
2723 window->consumeMotionMove();
2724 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2725
2726 // Now the foreground window goes away
2727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2728 window->consumeMotionCancel();
2729 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2730
2731 // If more events come in, there will be no more foreground window to send them to. This will
2732 // cause a cancel for the monitor, as well.
2733 ASSERT_EQ(InputEventInjectionResult::FAILED,
2734 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2735 ADISPLAY_ID_DEFAULT, {120, 200}))
2736 << "Injection should fail because the window was removed";
2737 window->assertNoEvents();
2738 // Global monitor now gets the cancel
2739 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2740}
2741
Michael Wright3a240c42019-12-10 20:53:41 +00002742// Tests for gesture monitors
2743TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002745 sp<FakeWindowHandle> window =
2746 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002748
chaviwd1c23182019-12-20 18:44:56 -08002749 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2750 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002751
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002753 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002754 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002755 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002756 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002757}
2758
2759TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002761 sp<FakeWindowHandle> window =
2762 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2763
2764 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002765 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002766
Arthur Hung72d8dc32020-03-28 00:48:39 +00002767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002768 setFocusedWindow(window);
2769
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002770 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002771
chaviwd1c23182019-12-20 18:44:56 -08002772 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2773 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002774
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2776 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002777 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002778 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002779}
2780
2781TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002782 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002783 sp<FakeWindowHandle> window =
2784 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002786
chaviwd1c23182019-12-20 18:44:56 -08002787 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2788 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002791 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002793 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002794 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002795
2796 window->releaseChannel();
2797
chaviwd1c23182019-12-20 18:44:56 -08002798 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002799
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002801 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002802 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002803 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002804}
2805
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002806TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2807 FakeMonitorReceiver monitor =
2808 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2809 true /*isGestureMonitor*/);
2810
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2813 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2814 ASSERT_TRUE(consumeSeq);
2815
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002816 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002817 monitor.finishEvent(*consumeSeq);
2818 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002819 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002820}
2821
Evan Rosky84f07f02021-04-16 10:42:42 -07002822// Tests for gesture monitors
2823TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2825 sp<FakeWindowHandle> window =
2826 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2828 window->setWindowOffset(20, 40);
2829 window->setWindowTransform(0, 1, -1, 0);
2830
2831 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2832 true /*isGestureMonitor*/);
2833
2834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2835 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2836 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2837 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2838 MotionEvent* event = monitor.consumeMotion();
2839 // Even though window has transform, gesture monitor must not.
2840 ASSERT_EQ(ui::Transform(), event->getTransform());
2841}
2842
Arthur Hungb3307ee2021-10-14 10:57:37 +00002843TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2844 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2845 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2846 true /*isGestureMonitor*/);
2847
2848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2849 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2850 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2851 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2852}
2853
chaviw81e2bb92019-12-18 15:03:51 -08002854TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002856 sp<FakeWindowHandle> window =
2857 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2858
Arthur Hung72d8dc32020-03-28 00:48:39 +00002859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002860
2861 NotifyMotionArgs motionArgs =
2862 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2863 ADISPLAY_ID_DEFAULT);
2864
2865 mDispatcher->notifyMotion(&motionArgs);
2866 // Window should receive motion down event.
2867 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2868
2869 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002870 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002871 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2872 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2873 motionArgs.pointerCoords[0].getX() - 10);
2874
2875 mDispatcher->notifyMotion(&motionArgs);
2876 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2877 0 /*expectedFlags*/);
2878}
2879
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002880/**
2881 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2882 * the device default right away. In the test scenario, we check both the default value,
2883 * and the action of enabling / disabling.
2884 */
2885TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002886 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002887 sp<FakeWindowHandle> window =
2888 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2889
2890 // Set focused application.
2891 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002892 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002893
2894 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002896 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002897 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2898
2899 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002900 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002902 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2903
2904 SCOPED_TRACE("Disable touch mode");
2905 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002906 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002907 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002909 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002910 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2911
2912 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002913 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002914 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002915 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2916
2917 SCOPED_TRACE("Enable touch mode again");
2918 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002919 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002920 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002922 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002923 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2924
2925 window->assertNoEvents();
2926}
2927
Gang Wange9087892020-01-07 12:17:14 -05002928TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002929 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002930 sp<FakeWindowHandle> window =
2931 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2932
2933 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002934 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002935
Arthur Hung72d8dc32020-03-28 00:48:39 +00002936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002937 setFocusedWindow(window);
2938
Gang Wange9087892020-01-07 12:17:14 -05002939 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2940
2941 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2942 mDispatcher->notifyKey(&keyArgs);
2943
2944 InputEvent* event = window->consume();
2945 ASSERT_NE(event, nullptr);
2946
2947 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2948 ASSERT_NE(verified, nullptr);
2949 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2950
2951 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2952 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2953 ASSERT_EQ(keyArgs.source, verified->source);
2954 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2955
2956 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2957
2958 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2959 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002960 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2961 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2962 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2963 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2964 ASSERT_EQ(0, verifiedKey.repeatCount);
2965}
2966
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002967TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002968 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002969 sp<FakeWindowHandle> window =
2970 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2971
2972 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2973
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002974 ui::Transform transform;
2975 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
2976
2977 gui::DisplayInfo displayInfo;
2978 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
2979 displayInfo.transform = transform;
2980
2981 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002982
2983 NotifyMotionArgs motionArgs =
2984 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2985 ADISPLAY_ID_DEFAULT);
2986 mDispatcher->notifyMotion(&motionArgs);
2987
2988 InputEvent* event = window->consume();
2989 ASSERT_NE(event, nullptr);
2990
2991 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2992 ASSERT_NE(verified, nullptr);
2993 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2994
2995 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2996 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2997 EXPECT_EQ(motionArgs.source, verified->source);
2998 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2999
3000 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3001
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003002 const vec2 rawXY =
3003 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3004 motionArgs.pointerCoords[0].getXYValue());
3005 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3006 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003007 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3008 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3009 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3010 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3011 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3012}
3013
chaviw09c8d2d2020-08-24 15:48:26 -07003014/**
3015 * Ensure that separate calls to sign the same data are generating the same key.
3016 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3017 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3018 * tests.
3019 */
3020TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3021 KeyEvent event = getTestKeyEvent();
3022 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3023
3024 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3025 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3026 ASSERT_EQ(hmac1, hmac2);
3027}
3028
3029/**
3030 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3031 */
3032TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3033 KeyEvent event = getTestKeyEvent();
3034 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3035 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3036
3037 verifiedEvent.deviceId += 1;
3038 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3039
3040 verifiedEvent.source += 1;
3041 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3042
3043 verifiedEvent.eventTimeNanos += 1;
3044 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3045
3046 verifiedEvent.displayId += 1;
3047 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3048
3049 verifiedEvent.action += 1;
3050 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3051
3052 verifiedEvent.downTimeNanos += 1;
3053 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3054
3055 verifiedEvent.flags += 1;
3056 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3057
3058 verifiedEvent.keyCode += 1;
3059 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3060
3061 verifiedEvent.scanCode += 1;
3062 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3063
3064 verifiedEvent.metaState += 1;
3065 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3066
3067 verifiedEvent.repeatCount += 1;
3068 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3069}
3070
Vishnu Nair958da932020-08-21 17:12:37 -07003071TEST_F(InputDispatcherTest, SetFocusedWindow) {
3072 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3073 sp<FakeWindowHandle> windowTop =
3074 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3075 sp<FakeWindowHandle> windowSecond =
3076 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3077 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3078
3079 // Top window is also focusable but is not granted focus.
3080 windowTop->setFocusable(true);
3081 windowSecond->setFocusable(true);
3082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3083 setFocusedWindow(windowSecond);
3084
3085 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3087 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003088
3089 // Focused window should receive event.
3090 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3091 windowTop->assertNoEvents();
3092}
3093
3094TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3095 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3096 sp<FakeWindowHandle> window =
3097 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3098 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3099
3100 window->setFocusable(true);
3101 // Release channel for window is no longer valid.
3102 window->releaseChannel();
3103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3104 setFocusedWindow(window);
3105
3106 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003107 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3108 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003109
3110 // window channel is invalid, so it should not receive any input event.
3111 window->assertNoEvents();
3112}
3113
3114TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3116 sp<FakeWindowHandle> window =
3117 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3118 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3119
3120 // Window is not focusable.
3121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3122 setFocusedWindow(window);
3123
3124 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003125 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3126 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003127
3128 // window is invalid, so it should not receive any input event.
3129 window->assertNoEvents();
3130}
3131
3132TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3133 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3134 sp<FakeWindowHandle> windowTop =
3135 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3136 sp<FakeWindowHandle> windowSecond =
3137 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3138 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3139
3140 windowTop->setFocusable(true);
3141 windowSecond->setFocusable(true);
3142 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3143 setFocusedWindow(windowTop);
3144 windowTop->consumeFocusEvent(true);
3145
3146 setFocusedWindow(windowSecond, windowTop);
3147 windowSecond->consumeFocusEvent(true);
3148 windowTop->consumeFocusEvent(false);
3149
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3151 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003152
3153 // Focused window should receive event.
3154 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3155}
3156
3157TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3158 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3159 sp<FakeWindowHandle> windowTop =
3160 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3161 sp<FakeWindowHandle> windowSecond =
3162 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3163 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3164
3165 windowTop->setFocusable(true);
3166 windowSecond->setFocusable(true);
3167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3168 setFocusedWindow(windowSecond, windowTop);
3169
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003170 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3171 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003172
3173 // Event should be dropped.
3174 windowTop->assertNoEvents();
3175 windowSecond->assertNoEvents();
3176}
3177
3178TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3180 sp<FakeWindowHandle> window =
3181 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3182 sp<FakeWindowHandle> previousFocusedWindow =
3183 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3184 ADISPLAY_ID_DEFAULT);
3185 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3186
3187 window->setFocusable(true);
3188 previousFocusedWindow->setFocusable(true);
3189 window->setVisible(false);
3190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3191 setFocusedWindow(previousFocusedWindow);
3192 previousFocusedWindow->consumeFocusEvent(true);
3193
3194 // Requesting focus on invisible window takes focus from currently focused window.
3195 setFocusedWindow(window);
3196 previousFocusedWindow->consumeFocusEvent(false);
3197
3198 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003200 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003201 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003202
3203 // Window does not get focus event or key down.
3204 window->assertNoEvents();
3205
3206 // Window becomes visible.
3207 window->setVisible(true);
3208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3209
3210 // Window receives focus event.
3211 window->consumeFocusEvent(true);
3212 // Focused window receives key down.
3213 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3214}
3215
Vishnu Nair599f1412021-06-21 10:39:58 -07003216TEST_F(InputDispatcherTest, DisplayRemoved) {
3217 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3218 sp<FakeWindowHandle> window =
3219 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3220 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3221
3222 // window is granted focus.
3223 window->setFocusable(true);
3224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3225 setFocusedWindow(window);
3226 window->consumeFocusEvent(true);
3227
3228 // When a display is removed window loses focus.
3229 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3230 window->consumeFocusEvent(false);
3231}
3232
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003233/**
3234 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3235 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3236 * of the 'slipperyEnterWindow'.
3237 *
3238 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3239 * a way so that the touched location is no longer covered by the top window.
3240 *
3241 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3242 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3243 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3244 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3245 * with ACTION_DOWN).
3246 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3247 * window moved itself away from the touched location and had Flag::SLIPPERY.
3248 *
3249 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3250 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3251 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3252 *
3253 * In this test, we ensure that the event received by the bottom window has
3254 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3255 */
3256TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3257 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3258 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3259
3260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3261 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3262
3263 sp<FakeWindowHandle> slipperyExitWindow =
3264 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003265 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003266 // Make sure this one overlaps the bottom window
3267 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3268 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3269 // one. Windows with the same owner are not considered to be occluding each other.
3270 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3271
3272 sp<FakeWindowHandle> slipperyEnterWindow =
3273 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3274 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3275
3276 mDispatcher->setInputWindows(
3277 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3278
3279 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3280 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3281 ADISPLAY_ID_DEFAULT, {{50, 50}});
3282 mDispatcher->notifyMotion(&args);
3283 slipperyExitWindow->consumeMotionDown();
3284 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3285 mDispatcher->setInputWindows(
3286 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3287
3288 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3289 ADISPLAY_ID_DEFAULT, {{51, 51}});
3290 mDispatcher->notifyMotion(&args);
3291
3292 slipperyExitWindow->consumeMotionCancel();
3293
3294 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3295 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3296}
3297
Garfield Tan1c7bc862020-01-28 13:24:04 -08003298class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3299protected:
3300 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3301 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3302
Chris Yea209fde2020-07-22 13:54:51 -07003303 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003304 sp<FakeWindowHandle> mWindow;
3305
3306 virtual void SetUp() override {
3307 mFakePolicy = new FakeInputDispatcherPolicy();
3308 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003309 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003310 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3311 ASSERT_EQ(OK, mDispatcher->start());
3312
3313 setUpWindow();
3314 }
3315
3316 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003317 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003318 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3319
Vishnu Nair47074b82020-08-14 11:54:47 -07003320 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003322 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003323 mWindow->consumeFocusEvent(true);
3324 }
3325
Chris Ye2ad95392020-09-01 13:44:44 -07003326 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003327 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003328 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003329 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3330 mDispatcher->notifyKey(&keyArgs);
3331
3332 // Window should receive key down event.
3333 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3334 }
3335
3336 void expectKeyRepeatOnce(int32_t repeatCount) {
3337 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3338 InputEvent* repeatEvent = mWindow->consume();
3339 ASSERT_NE(nullptr, repeatEvent);
3340
3341 uint32_t eventType = repeatEvent->getType();
3342 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3343
3344 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3345 uint32_t eventAction = repeatKeyEvent->getAction();
3346 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3347 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3348 }
3349
Chris Ye2ad95392020-09-01 13:44:44 -07003350 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003351 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003352 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003353 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3354 mDispatcher->notifyKey(&keyArgs);
3355
3356 // Window should receive key down event.
3357 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3358 0 /*expectedFlags*/);
3359 }
3360};
3361
3362TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003363 sendAndConsumeKeyDown(1 /* deviceId */);
3364 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3365 expectKeyRepeatOnce(repeatCount);
3366 }
3367}
3368
3369TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3370 sendAndConsumeKeyDown(1 /* deviceId */);
3371 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3372 expectKeyRepeatOnce(repeatCount);
3373 }
3374 sendAndConsumeKeyDown(2 /* deviceId */);
3375 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003376 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3377 expectKeyRepeatOnce(repeatCount);
3378 }
3379}
3380
3381TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003382 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003383 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003384 sendAndConsumeKeyUp(1 /* deviceId */);
3385 mWindow->assertNoEvents();
3386}
3387
3388TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3389 sendAndConsumeKeyDown(1 /* deviceId */);
3390 expectKeyRepeatOnce(1 /*repeatCount*/);
3391 sendAndConsumeKeyDown(2 /* deviceId */);
3392 expectKeyRepeatOnce(1 /*repeatCount*/);
3393 // Stale key up from device 1.
3394 sendAndConsumeKeyUp(1 /* deviceId */);
3395 // Device 2 is still down, keep repeating
3396 expectKeyRepeatOnce(2 /*repeatCount*/);
3397 expectKeyRepeatOnce(3 /*repeatCount*/);
3398 // Device 2 key up
3399 sendAndConsumeKeyUp(2 /* deviceId */);
3400 mWindow->assertNoEvents();
3401}
3402
3403TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3404 sendAndConsumeKeyDown(1 /* deviceId */);
3405 expectKeyRepeatOnce(1 /*repeatCount*/);
3406 sendAndConsumeKeyDown(2 /* deviceId */);
3407 expectKeyRepeatOnce(1 /*repeatCount*/);
3408 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3409 sendAndConsumeKeyUp(2 /* deviceId */);
3410 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003411 mWindow->assertNoEvents();
3412}
3413
liushenxiang42232912021-05-21 20:24:09 +08003414TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3415 sendAndConsumeKeyDown(DEVICE_ID);
3416 expectKeyRepeatOnce(1 /*repeatCount*/);
3417 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3418 mDispatcher->notifyDeviceReset(&args);
3419 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3420 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3421 mWindow->assertNoEvents();
3422}
3423
Garfield Tan1c7bc862020-01-28 13:24:04 -08003424TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003425 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003426 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3427 InputEvent* repeatEvent = mWindow->consume();
3428 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3429 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3430 IdGenerator::getSource(repeatEvent->getId()));
3431 }
3432}
3433
3434TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003435 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003436
3437 std::unordered_set<int32_t> idSet;
3438 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3439 InputEvent* repeatEvent = mWindow->consume();
3440 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3441 int32_t id = repeatEvent->getId();
3442 EXPECT_EQ(idSet.end(), idSet.find(id));
3443 idSet.insert(id);
3444 }
3445}
3446
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003447/* Test InputDispatcher for MultiDisplay */
3448class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3449public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003450 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003451 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003452
Chris Yea209fde2020-07-22 13:54:51 -07003453 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003454 windowInPrimary =
3455 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003456
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003457 // Set focus window for primary display, but focused display would be second one.
3458 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003459 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003461 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003462 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003463
Chris Yea209fde2020-07-22 13:54:51 -07003464 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003465 windowInSecondary =
3466 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003467 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003468 // Set focus display to second one.
3469 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3470 // Set focus window for second display.
3471 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003472 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003473 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003474 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003475 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003476 }
3477
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003478 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003479 InputDispatcherTest::TearDown();
3480
Chris Yea209fde2020-07-22 13:54:51 -07003481 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003482 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003483 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003484 windowInSecondary.clear();
3485 }
3486
3487protected:
Chris Yea209fde2020-07-22 13:54:51 -07003488 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003489 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003490 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003491 sp<FakeWindowHandle> windowInSecondary;
3492};
3493
3494TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3495 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3497 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003499 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003500 windowInSecondary->assertNoEvents();
3501
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003502 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3504 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3505 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003506 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003507 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003508}
3509
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003510TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003511 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3513 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003514 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003515 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003516 windowInSecondary->assertNoEvents();
3517
3518 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003520 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003521 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003522 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003523
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003524 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003525 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003527 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003528 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3529 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003530
3531 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003532 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003533 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003534 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003535 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003536 windowInSecondary->assertNoEvents();
3537}
3538
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003539// Test per-display input monitors for motion event.
3540TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003541 FakeMonitorReceiver monitorInPrimary =
3542 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3543 FakeMonitorReceiver monitorInSecondary =
3544 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003545
3546 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3548 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3549 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003550 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003551 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003552 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003553 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003554
3555 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3558 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003559 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003560 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003561 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003562 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003563
3564 // Test inject a non-pointer motion event.
3565 // If specific a display, it will dispatch to the focused window of particular display,
3566 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3568 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003570 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003571 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003572 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003573 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003574}
3575
3576// Test per-display input monitors for key event.
3577TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003578 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003579 FakeMonitorReceiver monitorInPrimary =
3580 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3581 FakeMonitorReceiver monitorInSecondary =
3582 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003583
3584 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3586 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003587 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003588 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003589 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003590 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003591}
3592
Vishnu Nair958da932020-08-21 17:12:37 -07003593TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3594 sp<FakeWindowHandle> secondWindowInPrimary =
3595 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3596 secondWindowInPrimary->setFocusable(true);
3597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3598 setFocusedWindow(secondWindowInPrimary);
3599 windowInPrimary->consumeFocusEvent(false);
3600 secondWindowInPrimary->consumeFocusEvent(true);
3601
3602 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3604 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003605 windowInPrimary->assertNoEvents();
3606 windowInSecondary->assertNoEvents();
3607 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3608}
3609
Jackal Guof9696682018-10-05 12:23:23 +08003610class InputFilterTest : public InputDispatcherTest {
3611protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003612 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3613 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003614 NotifyMotionArgs motionArgs;
3615
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003616 motionArgs =
3617 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003618 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003619 motionArgs =
3620 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003621 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003622 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003623 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003624 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3625 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003626 } else {
3627 mFakePolicy->assertFilterInputEventWasNotCalled();
3628 }
3629 }
3630
3631 void testNotifyKey(bool expectToBeFiltered) {
3632 NotifyKeyArgs keyArgs;
3633
3634 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3635 mDispatcher->notifyKey(&keyArgs);
3636 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3637 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003638 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003639
3640 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003641 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003642 } else {
3643 mFakePolicy->assertFilterInputEventWasNotCalled();
3644 }
3645 }
3646};
3647
3648// Test InputFilter for MotionEvent
3649TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3650 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3651 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3652 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3653
3654 // Enable InputFilter
3655 mDispatcher->setInputFilterEnabled(true);
3656 // Test touch on both primary and second display, and check if both events are filtered.
3657 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3658 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3659
3660 // Disable InputFilter
3661 mDispatcher->setInputFilterEnabled(false);
3662 // Test touch on both primary and second display, and check if both events aren't filtered.
3663 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3664 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3665}
3666
3667// Test InputFilter for KeyEvent
3668TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3669 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3670 testNotifyKey(/*expectToBeFiltered*/ false);
3671
3672 // Enable InputFilter
3673 mDispatcher->setInputFilterEnabled(true);
3674 // Send a key event, and check if it is filtered.
3675 testNotifyKey(/*expectToBeFiltered*/ true);
3676
3677 // Disable InputFilter
3678 mDispatcher->setInputFilterEnabled(false);
3679 // Send a key event, and check if it isn't filtered.
3680 testNotifyKey(/*expectToBeFiltered*/ false);
3681}
3682
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003683// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3684// logical display coordinate space.
3685TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3686 ui::Transform firstDisplayTransform;
3687 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3688 ui::Transform secondDisplayTransform;
3689 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3690
3691 std::vector<gui::DisplayInfo> displayInfos(2);
3692 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3693 displayInfos[0].transform = firstDisplayTransform;
3694 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3695 displayInfos[1].transform = secondDisplayTransform;
3696
3697 mDispatcher->onWindowInfosChanged({}, displayInfos);
3698
3699 // Enable InputFilter
3700 mDispatcher->setInputFilterEnabled(true);
3701
3702 // Ensure the correct transforms are used for the displays.
3703 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3704 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3705}
3706
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003707class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3708protected:
3709 virtual void SetUp() override {
3710 InputDispatcherTest::SetUp();
3711
3712 /**
3713 * We don't need to enable input filter to test the injected event policy, but we enabled it
3714 * here to make the tests more realistic, since this policy only matters when inputfilter is
3715 * on.
3716 */
3717 mDispatcher->setInputFilterEnabled(true);
3718
3719 std::shared_ptr<InputApplicationHandle> application =
3720 std::make_shared<FakeApplicationHandle>();
3721 mWindow =
3722 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3723
3724 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3725 mWindow->setFocusable(true);
3726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3727 setFocusedWindow(mWindow);
3728 mWindow->consumeFocusEvent(true);
3729 }
3730
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003731 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3732 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003733 KeyEvent event;
3734
3735 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3736 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3737 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3738 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3739 const int32_t additionalPolicyFlags =
3740 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3741 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3742 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3743 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3744 policyFlags | additionalPolicyFlags));
3745
3746 InputEvent* received = mWindow->consume();
3747 ASSERT_NE(nullptr, received);
3748 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003749 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3750 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3751 ASSERT_EQ(flags, keyEvent.getFlags());
3752 }
3753
3754 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3755 int32_t flags) {
3756 MotionEvent event;
3757 PointerProperties pointerProperties[1];
3758 PointerCoords pointerCoords[1];
3759 pointerProperties[0].clear();
3760 pointerProperties[0].id = 0;
3761 pointerCoords[0].clear();
3762 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3763 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3764
3765 ui::Transform identityTransform;
3766 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3767 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3768 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3769 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3770 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003771 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003772 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003773 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3774
3775 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3777 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3778 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3779 policyFlags | additionalPolicyFlags));
3780
3781 InputEvent* received = mWindow->consume();
3782 ASSERT_NE(nullptr, received);
3783 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3784 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3785 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3786 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003787 }
3788
3789private:
3790 sp<FakeWindowHandle> mWindow;
3791};
3792
3793TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003794 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3795 // filter. Without it, the event will no different from a regularly injected event, and the
3796 // injected device id will be overwritten.
3797 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3798 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003799}
3800
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003801TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003802 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003803 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3804 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3805}
3806
3807TEST_F(InputFilterInjectionPolicyTest,
3808 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3809 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3810 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3811 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003812}
3813
3814TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3815 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003816 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003817}
3818
chaviwfd6d3512019-03-25 13:23:49 -07003819class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003820 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003821 InputDispatcherTest::SetUp();
3822
Chris Yea209fde2020-07-22 13:54:51 -07003823 std::shared_ptr<FakeApplicationHandle> application =
3824 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003825 mUnfocusedWindow =
3826 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003827 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3828 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3829 // window.
chaviw3277faf2021-05-19 16:45:23 -05003830 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003831
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003832 mFocusedWindow =
3833 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3834 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003835 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003836
3837 // Set focused application.
3838 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003839 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003840
3841 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003843 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003844 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003845 }
3846
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003847 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003848 InputDispatcherTest::TearDown();
3849
3850 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003851 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003852 }
3853
3854protected:
3855 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003856 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003857 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003858};
3859
3860// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3861// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3862// the onPointerDownOutsideFocus callback.
3863TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003865 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3866 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003868 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003869
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003870 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003871 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3872}
3873
3874// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3875// DOWN on the window that doesn't have focus. Ensure no window received the
3876// onPointerDownOutsideFocus callback.
3877TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003879 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003881 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003882
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003883 ASSERT_TRUE(mDispatcher->waitForIdle());
3884 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003885}
3886
3887// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3888// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3889TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3891 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003892 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003893 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003894
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003895 ASSERT_TRUE(mDispatcher->waitForIdle());
3896 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003897}
3898
3899// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3900// DOWN on the window that already has focus. Ensure no window received the
3901// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003902TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003904 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003905 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003907 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003908
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003909 ASSERT_TRUE(mDispatcher->waitForIdle());
3910 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003911}
3912
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003913// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3914// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3915TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3916 const MotionEvent event =
3917 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3918 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3919 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3920 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3921 .build();
3922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3923 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3924 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3925
3926 ASSERT_TRUE(mDispatcher->waitForIdle());
3927 mFakePolicy->assertOnPointerDownWasNotCalled();
3928 // Ensure that the unfocused window did not receive any FOCUS events.
3929 mUnfocusedWindow->assertNoEvents();
3930}
3931
chaviwaf87b3e2019-10-01 16:59:28 -07003932// These tests ensures we can send touch events to a single client when there are multiple input
3933// windows that point to the same client token.
3934class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3935 virtual void SetUp() override {
3936 InputDispatcherTest::SetUp();
3937
Chris Yea209fde2020-07-22 13:54:51 -07003938 std::shared_ptr<FakeApplicationHandle> application =
3939 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003940 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3941 ADISPLAY_ID_DEFAULT);
3942 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3943 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003944 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003945 mWindow1->setFrame(Rect(0, 0, 100, 100));
3946
3947 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3948 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003949 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003950 mWindow2->setFrame(Rect(100, 100, 200, 200));
3951
Arthur Hung72d8dc32020-03-28 00:48:39 +00003952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003953 }
3954
3955protected:
3956 sp<FakeWindowHandle> mWindow1;
3957 sp<FakeWindowHandle> mWindow2;
3958
3959 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003960 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003961 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3962 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003963 }
3964
3965 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3966 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003967 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003968 InputEvent* event = window->consume();
3969
3970 ASSERT_NE(nullptr, event) << name.c_str()
3971 << ": consumer should have returned non-NULL event.";
3972
3973 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3974 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3975 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3976
3977 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003978 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07003979
3980 for (size_t i = 0; i < points.size(); i++) {
3981 float expectedX = points[i].x;
3982 float expectedY = points[i].y;
3983
3984 EXPECT_EQ(expectedX, motionEvent.getX(i))
3985 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3986 << ", got " << motionEvent.getX(i);
3987 EXPECT_EQ(expectedY, motionEvent.getY(i))
3988 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3989 << ", got " << motionEvent.getY(i);
3990 }
3991 }
chaviw9eaa22c2020-07-01 16:21:27 -07003992
3993 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3994 std::vector<PointF> expectedPoints) {
3995 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3996 ADISPLAY_ID_DEFAULT, touchedPoints);
3997 mDispatcher->notifyMotion(&motionArgs);
3998
3999 // Always consume from window1 since it's the window that has the InputReceiver
4000 consumeMotionEvent(mWindow1, action, expectedPoints);
4001 }
chaviwaf87b3e2019-10-01 16:59:28 -07004002};
4003
4004TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4005 // Touch Window 1
4006 PointF touchedPoint = {10, 10};
4007 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004008 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004009
4010 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004011 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004012
4013 // Touch Window 2
4014 touchedPoint = {150, 150};
4015 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004016 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004017}
4018
chaviw9eaa22c2020-07-01 16:21:27 -07004019TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4020 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004021 mWindow2->setWindowScale(0.5f, 0.5f);
4022
4023 // Touch Window 1
4024 PointF touchedPoint = {10, 10};
4025 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004026 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004027 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004028 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004029
4030 // Touch Window 2
4031 touchedPoint = {150, 150};
4032 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004033 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4034 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004035
chaviw9eaa22c2020-07-01 16:21:27 -07004036 // Update the transform so rotation is set
4037 mWindow2->setWindowTransform(0, -1, 1, 0);
4038 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4039 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004040}
4041
chaviw9eaa22c2020-07-01 16:21:27 -07004042TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004043 mWindow2->setWindowScale(0.5f, 0.5f);
4044
4045 // Touch Window 1
4046 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4047 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004048 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004049
4050 // Touch Window 2
4051 int32_t actionPointerDown =
4052 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004053 touchedPoints.push_back(PointF{150, 150});
4054 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4055 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004056
chaviw9eaa22c2020-07-01 16:21:27 -07004057 // Release Window 2
4058 int32_t actionPointerUp =
4059 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4060 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4061 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004062
chaviw9eaa22c2020-07-01 16:21:27 -07004063 // Update the transform so rotation is set for Window 2
4064 mWindow2->setWindowTransform(0, -1, 1, 0);
4065 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4066 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004067}
4068
chaviw9eaa22c2020-07-01 16:21:27 -07004069TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004070 mWindow2->setWindowScale(0.5f, 0.5f);
4071
4072 // Touch Window 1
4073 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4074 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004075 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004076
4077 // Touch Window 2
4078 int32_t actionPointerDown =
4079 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004080 touchedPoints.push_back(PointF{150, 150});
4081 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004082
chaviw9eaa22c2020-07-01 16:21:27 -07004083 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004084
4085 // Move both windows
4086 touchedPoints = {{20, 20}, {175, 175}};
4087 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4088 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4089
chaviw9eaa22c2020-07-01 16:21:27 -07004090 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004091
chaviw9eaa22c2020-07-01 16:21:27 -07004092 // Release Window 2
4093 int32_t actionPointerUp =
4094 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4095 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4096 expectedPoints.pop_back();
4097
4098 // Touch Window 2
4099 mWindow2->setWindowTransform(0, -1, 1, 0);
4100 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4101 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4102
4103 // Move both windows
4104 touchedPoints = {{20, 20}, {175, 175}};
4105 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4106 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4107
4108 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004109}
4110
4111TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4112 mWindow1->setWindowScale(0.5f, 0.5f);
4113
4114 // Touch Window 1
4115 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4116 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004117 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004118
4119 // Touch Window 2
4120 int32_t actionPointerDown =
4121 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004122 touchedPoints.push_back(PointF{150, 150});
4123 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004124
chaviw9eaa22c2020-07-01 16:21:27 -07004125 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004126
4127 // Move both windows
4128 touchedPoints = {{20, 20}, {175, 175}};
4129 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4130 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4131
chaviw9eaa22c2020-07-01 16:21:27 -07004132 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004133}
4134
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004135class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4136 virtual void SetUp() override {
4137 InputDispatcherTest::SetUp();
4138
Chris Yea209fde2020-07-22 13:54:51 -07004139 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004140 mApplication->setDispatchingTimeout(20ms);
4141 mWindow =
4142 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4143 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004144 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004145 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004146 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4147 // window.
chaviw3277faf2021-05-19 16:45:23 -05004148 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004149
4150 // Set focused application.
4151 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4152
4153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004154 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004155 mWindow->consumeFocusEvent(true);
4156 }
4157
4158 virtual void TearDown() override {
4159 InputDispatcherTest::TearDown();
4160 mWindow.clear();
4161 }
4162
4163protected:
Chris Yea209fde2020-07-22 13:54:51 -07004164 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004165 sp<FakeWindowHandle> mWindow;
4166 static constexpr PointF WINDOW_LOCATION = {20, 20};
4167
4168 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004170 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4171 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004173 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4174 WINDOW_LOCATION));
4175 }
4176};
4177
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004178// Send a tap and respond, which should not cause an ANR.
4179TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4180 tapOnWindow();
4181 mWindow->consumeMotionDown();
4182 mWindow->consumeMotionUp();
4183 ASSERT_TRUE(mDispatcher->waitForIdle());
4184 mFakePolicy->assertNotifyAnrWasNotCalled();
4185}
4186
4187// Send a regular key and respond, which should not cause an ANR.
4188TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004189 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004190 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4191 ASSERT_TRUE(mDispatcher->waitForIdle());
4192 mFakePolicy->assertNotifyAnrWasNotCalled();
4193}
4194
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004195TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4196 mWindow->setFocusable(false);
4197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4198 mWindow->consumeFocusEvent(false);
4199
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004200 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004201 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004202 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4203 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004204 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004205 // Key will not go to window because we have no focused window.
4206 // The 'no focused window' ANR timer should start instead.
4207
4208 // Now, the focused application goes away.
4209 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4210 // The key should get dropped and there should be no ANR.
4211
4212 ASSERT_TRUE(mDispatcher->waitForIdle());
4213 mFakePolicy->assertNotifyAnrWasNotCalled();
4214}
4215
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004216// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004217// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4218// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004219TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004221 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4222 WINDOW_LOCATION));
4223
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004224 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4225 ASSERT_TRUE(sequenceNum);
4226 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004227 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004228
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004229 mWindow->finishEvent(*sequenceNum);
4230 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4231 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004232 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004233 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004234}
4235
4236// Send a key to the app and have the app not respond right away.
4237TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4238 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004240 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4241 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004242 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004243 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004244 ASSERT_TRUE(mDispatcher->waitForIdle());
4245}
4246
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004247// We have a focused application, but no focused window
4248TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004249 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4251 mWindow->consumeFocusEvent(false);
4252
4253 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004255 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4256 WINDOW_LOCATION));
4257 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4258 mDispatcher->waitForIdle();
4259 mFakePolicy->assertNotifyAnrWasNotCalled();
4260
4261 // Once a focused event arrives, we get an ANR for this application
4262 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4263 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004265 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004266 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004267 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004268 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004269 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004270 ASSERT_TRUE(mDispatcher->waitForIdle());
4271}
4272
4273// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004274// Make sure that we don't notify policy twice about the same ANR.
4275TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004276 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004277 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4278 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004279
4280 // Once a focused event arrives, we get an ANR for this application
4281 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4282 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004284 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004285 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004287 const std::chrono::duration appTimeout =
4288 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004289 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004290
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004291 std::this_thread::sleep_for(appTimeout);
4292 // ANR should not be raised again. It is up to policy to do that if it desires.
4293 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004294
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004295 // If we now get a focused window, the ANR should stop, but the policy handles that via
4296 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004297 ASSERT_TRUE(mDispatcher->waitForIdle());
4298}
4299
4300// We have a focused application, but no focused window
4301TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004302 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4304 mWindow->consumeFocusEvent(false);
4305
4306 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004308 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4310 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004311
4312 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004313 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004314
4315 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004316 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004317 ASSERT_TRUE(mDispatcher->waitForIdle());
4318 mWindow->assertNoEvents();
4319}
4320
4321/**
4322 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4323 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4324 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4325 * the ANR mechanism should still work.
4326 *
4327 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4328 * DOWN event, while not responding on the second one.
4329 */
4330TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4331 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4332 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4333 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4334 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4335 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004337
4338 // Now send ACTION_UP, with identical timestamp
4339 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4340 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4341 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4342 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004343 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344
4345 // We have now sent down and up. Let's consume first event and then ANR on the second.
4346 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4347 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004348 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004349}
4350
4351// If an app is not responding to a key event, gesture monitors should continue to receive
4352// new motion events
4353TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4354 FakeMonitorReceiver monitor =
4355 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4356 true /*isGestureMonitor*/);
4357
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4359 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004360 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362
4363 // Stuck on the ACTION_UP
4364 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004365 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004366
4367 // New tap will go to the gesture monitor, but not to the window
4368 tapOnWindow();
4369 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4370 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4371
4372 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4373 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004374 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004375 mWindow->assertNoEvents();
4376 monitor.assertNoEvents();
4377}
4378
4379// If an app is not responding to a motion event, gesture monitors should continue to receive
4380// new motion events
4381TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4382 FakeMonitorReceiver monitor =
4383 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4384 true /*isGestureMonitor*/);
4385
4386 tapOnWindow();
4387 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4388 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4389
4390 mWindow->consumeMotionDown();
4391 // Stuck on the ACTION_UP
4392 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004393 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394
4395 // New tap will go to the gesture monitor, but not to the window
4396 tapOnWindow();
4397 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4398 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4399
4400 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4401 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004402 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004403 mWindow->assertNoEvents();
4404 monitor.assertNoEvents();
4405}
4406
4407// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4408// process events, you don't get an anr. When the window later becomes unresponsive again, you
4409// get an ANR again.
4410// 1. tap -> block on ACTION_UP -> receive ANR
4411// 2. consume all pending events (= queue becomes healthy again)
4412// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4413TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4414 tapOnWindow();
4415
4416 mWindow->consumeMotionDown();
4417 // Block on 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 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4421 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004422 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423 mWindow->assertNoEvents();
4424
4425 tapOnWindow();
4426 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004427 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004428 mWindow->consumeMotionUp();
4429
4430 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004431 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004432 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 mWindow->assertNoEvents();
4434}
4435
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004436// If a connection remains unresponsive for a while, make sure policy is only notified once about
4437// it.
4438TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004440 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4441 WINDOW_LOCATION));
4442
4443 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004444 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004445 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004446 // 'notifyConnectionUnresponsive' should only be called once per connection
4447 mFakePolicy->assertNotifyAnrWasNotCalled();
4448 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004449 mWindow->consumeMotionDown();
4450 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4451 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4452 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004453 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004454 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004455 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004456}
4457
4458/**
4459 * If a window is processing a motion event, and then a key event comes in, the key event should
4460 * not to to the focused window until the motion is processed.
4461 *
4462 * Warning!!!
4463 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4464 * and the injection timeout that we specify when injecting the key.
4465 * We must have the injection timeout (10ms) be smaller than
4466 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4467 *
4468 * If that value changes, this test should also change.
4469 */
4470TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4471 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4473
4474 tapOnWindow();
4475 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4476 ASSERT_TRUE(downSequenceNum);
4477 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4478 ASSERT_TRUE(upSequenceNum);
4479 // Don't finish the events yet, and send a key
4480 // Injection will "succeed" because we will eventually give up and send the key to the focused
4481 // window even if motions are still being processed. But because the injection timeout is short,
4482 // we will receive INJECTION_TIMED_OUT as the result.
4483
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004485 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004486 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4487 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004488 // Key will not be sent to the window, yet, because the window is still processing events
4489 // and the key remains pending, waiting for the touch events to be processed
4490 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4491 ASSERT_FALSE(keySequenceNum);
4492
4493 std::this_thread::sleep_for(500ms);
4494 // if we wait long enough though, dispatcher will give up, and still send the key
4495 // to the focused window, even though we have not yet finished the motion event
4496 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4497 mWindow->finishEvent(*downSequenceNum);
4498 mWindow->finishEvent(*upSequenceNum);
4499}
4500
4501/**
4502 * If a window is processing a motion event, and then a key event comes in, the key event should
4503 * not go to the focused window until the motion is processed.
4504 * If then a new motion comes in, then the pending key event should be going to the currently
4505 * focused window right away.
4506 */
4507TEST_F(InputDispatcherSingleWindowAnr,
4508 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4509 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4511
4512 tapOnWindow();
4513 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4514 ASSERT_TRUE(downSequenceNum);
4515 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4516 ASSERT_TRUE(upSequenceNum);
4517 // Don't finish the events yet, and send a key
4518 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004521 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004522 // At this point, key is still pending, and should not be sent to the application yet.
4523 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4524 ASSERT_FALSE(keySequenceNum);
4525
4526 // Now tap down again. It should cause the pending key to go to the focused window right away.
4527 tapOnWindow();
4528 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4529 // the other events yet. We can finish events in any order.
4530 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4531 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4532 mWindow->consumeMotionDown();
4533 mWindow->consumeMotionUp();
4534 mWindow->assertNoEvents();
4535}
4536
4537class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4538 virtual void SetUp() override {
4539 InputDispatcherTest::SetUp();
4540
Chris Yea209fde2020-07-22 13:54:51 -07004541 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542 mApplication->setDispatchingTimeout(10ms);
4543 mUnfocusedWindow =
4544 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4545 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4546 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4547 // window.
4548 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004549 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4550 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4551 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004552
4553 mFocusedWindow =
4554 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004555 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004557 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004558
4559 // Set focused application.
4560 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004561 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562
4563 // Expect one focus window exist in display.
4564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004565 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566 mFocusedWindow->consumeFocusEvent(true);
4567 }
4568
4569 virtual void TearDown() override {
4570 InputDispatcherTest::TearDown();
4571
4572 mUnfocusedWindow.clear();
4573 mFocusedWindow.clear();
4574 }
4575
4576protected:
Chris Yea209fde2020-07-22 13:54:51 -07004577 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578 sp<FakeWindowHandle> mUnfocusedWindow;
4579 sp<FakeWindowHandle> mFocusedWindow;
4580 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4581 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4582 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4583
4584 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4585
4586 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4587
4588private:
4589 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004591 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4592 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4595 location));
4596 }
4597};
4598
4599// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4600// should be ANR'd first.
4601TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4604 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606 mFocusedWindow->consumeMotionDown();
4607 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4608 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4609 // We consumed all events, so no ANR
4610 ASSERT_TRUE(mDispatcher->waitForIdle());
4611 mFakePolicy->assertNotifyAnrWasNotCalled();
4612
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4615 FOCUSED_WINDOW_LOCATION));
4616 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4617 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618
4619 const std::chrono::duration timeout =
4620 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004621 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004622 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4623 // sequence to make it consistent
4624 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004626 mFocusedWindow->consumeMotionDown();
4627 // This cancel is generated because the connection was unresponsive
4628 mFocusedWindow->consumeMotionCancel();
4629 mFocusedWindow->assertNoEvents();
4630 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004632 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004633 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004634}
4635
4636// If we have 2 windows with identical timeouts that are both unresponsive,
4637// it doesn't matter which order they should have ANR.
4638// But we should receive ANR for both.
4639TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4640 // Set the timeout for unfocused window to match the focused window
4641 mUnfocusedWindow->setDispatchingTimeout(10ms);
4642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4643
4644 tapOnFocusedWindow();
4645 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004646 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4647 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004648
4649 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004650 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4651 mFocusedWindow->getToken() == anrConnectionToken2);
4652 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4653 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004654
4655 ASSERT_TRUE(mDispatcher->waitForIdle());
4656 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004657
4658 mFocusedWindow->consumeMotionDown();
4659 mFocusedWindow->consumeMotionUp();
4660 mUnfocusedWindow->consumeMotionOutside();
4661
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004662 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4663 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004664
4665 // Both applications should be marked as responsive, in any order
4666 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4667 mFocusedWindow->getToken() == responsiveToken2);
4668 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4669 mUnfocusedWindow->getToken() == responsiveToken2);
4670 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004671}
4672
4673// If a window is already not responding, the second tap on the same window should be ignored.
4674// We should also log an error to account for the dropped event (not tested here).
4675// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4676TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4677 tapOnFocusedWindow();
4678 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4679 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4680 // Receive the events, but don't respond
4681 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4682 ASSERT_TRUE(downEventSequenceNum);
4683 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4684 ASSERT_TRUE(upEventSequenceNum);
4685 const std::chrono::duration timeout =
4686 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004687 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688
4689 // Tap once again
4690 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4693 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4696 FOCUSED_WINDOW_LOCATION));
4697 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4698 // valid touch target
4699 mUnfocusedWindow->assertNoEvents();
4700
4701 // Consume the first tap
4702 mFocusedWindow->finishEvent(*downEventSequenceNum);
4703 mFocusedWindow->finishEvent(*upEventSequenceNum);
4704 ASSERT_TRUE(mDispatcher->waitForIdle());
4705 // The second tap did not go to the focused window
4706 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004707 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004708 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 mFakePolicy->assertNotifyAnrWasNotCalled();
4710}
4711
4712// If you tap outside of all windows, there will not be ANR
4713TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004714 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004715 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4716 LOCATION_OUTSIDE_ALL_WINDOWS));
4717 ASSERT_TRUE(mDispatcher->waitForIdle());
4718 mFakePolicy->assertNotifyAnrWasNotCalled();
4719}
4720
4721// Since the focused window is paused, tapping on it should not produce any events
4722TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4723 mFocusedWindow->setPaused(true);
4724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4728 FOCUSED_WINDOW_LOCATION));
4729
4730 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4731 ASSERT_TRUE(mDispatcher->waitForIdle());
4732 // Should not ANR because the window is paused, and touches shouldn't go to it
4733 mFakePolicy->assertNotifyAnrWasNotCalled();
4734
4735 mFocusedWindow->assertNoEvents();
4736 mUnfocusedWindow->assertNoEvents();
4737}
4738
4739/**
4740 * If a window is processing a motion event, and then a key event comes in, the key event should
4741 * not to to the focused window until the motion is processed.
4742 * If a different window becomes focused at this time, the key should go to that window instead.
4743 *
4744 * Warning!!!
4745 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4746 * and the injection timeout that we specify when injecting the key.
4747 * We must have the injection timeout (10ms) be smaller than
4748 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4749 *
4750 * If that value changes, this test should also change.
4751 */
4752TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4753 // Set a long ANR timeout to prevent it from triggering
4754 mFocusedWindow->setDispatchingTimeout(2s);
4755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4756
4757 tapOnUnfocusedWindow();
4758 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4759 ASSERT_TRUE(downSequenceNum);
4760 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4761 ASSERT_TRUE(upSequenceNum);
4762 // Don't finish the events yet, and send a key
4763 // Injection will succeed because we will eventually give up and send the key to the focused
4764 // window even if motions are still being processed.
4765
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004766 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004767 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004768 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 // Key will not be sent to the window, yet, because the window is still processing events
4771 // and the key remains pending, waiting for the touch events to be processed
4772 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4773 ASSERT_FALSE(keySequenceNum);
4774
4775 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004776 mFocusedWindow->setFocusable(false);
4777 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004779 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780
4781 // Focus events should precede the key events
4782 mUnfocusedWindow->consumeFocusEvent(true);
4783 mFocusedWindow->consumeFocusEvent(false);
4784
4785 // Finish the tap events, which should unblock dispatcher
4786 mUnfocusedWindow->finishEvent(*downSequenceNum);
4787 mUnfocusedWindow->finishEvent(*upSequenceNum);
4788
4789 // Now that all queues are cleared and no backlog in the connections, the key event
4790 // can finally go to the newly focused "mUnfocusedWindow".
4791 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4792 mFocusedWindow->assertNoEvents();
4793 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004794 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795}
4796
4797// When the touch stream is split across 2 windows, and one of them does not respond,
4798// then ANR should be raised and the touch should be canceled for the unresponsive window.
4799// The other window should not be affected by that.
4800TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4801 // Touch Window 1
4802 NotifyMotionArgs motionArgs =
4803 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4804 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4805 mDispatcher->notifyMotion(&motionArgs);
4806 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4807 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4808
4809 // Touch Window 2
4810 int32_t actionPointerDown =
4811 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4812
4813 motionArgs =
4814 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4815 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4816 mDispatcher->notifyMotion(&motionArgs);
4817
4818 const std::chrono::duration timeout =
4819 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004820 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821
4822 mUnfocusedWindow->consumeMotionDown();
4823 mFocusedWindow->consumeMotionDown();
4824 // Focused window may or may not receive ACTION_MOVE
4825 // But it should definitely receive ACTION_CANCEL due to the ANR
4826 InputEvent* event;
4827 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4828 ASSERT_TRUE(moveOrCancelSequenceNum);
4829 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4830 ASSERT_NE(nullptr, event);
4831 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4832 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4833 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4834 mFocusedWindow->consumeMotionCancel();
4835 } else {
4836 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4837 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004839 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004840
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 mUnfocusedWindow->assertNoEvents();
4842 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004843 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844}
4845
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004846/**
4847 * If we have no focused window, and a key comes in, we start the ANR timer.
4848 * The focused application should add a focused window before the timer runs out to prevent ANR.
4849 *
4850 * If the user touches another application during this time, the key should be dropped.
4851 * Next, if a new focused window comes in, without toggling the focused application,
4852 * then no ANR should occur.
4853 *
4854 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4855 * but in some cases the policy may not update the focused application.
4856 */
4857TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4858 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4859 std::make_shared<FakeApplicationHandle>();
4860 focusedApplication->setDispatchingTimeout(60ms);
4861 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4862 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4863 mFocusedWindow->setFocusable(false);
4864
4865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4866 mFocusedWindow->consumeFocusEvent(false);
4867
4868 // Send a key. The ANR timer should start because there is no focused window.
4869 // 'focusedApplication' will get blamed if this timer completes.
4870 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004871 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004872 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004873 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4874 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004876
4877 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4878 // then the injected touches won't cause the focused event to get dropped.
4879 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4880 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4881 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4882 // For this test, it means that the key would get delivered to the window once it becomes
4883 // focused.
4884 std::this_thread::sleep_for(10ms);
4885
4886 // Touch unfocused window. This should force the pending key to get dropped.
4887 NotifyMotionArgs motionArgs =
4888 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4889 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4890 mDispatcher->notifyMotion(&motionArgs);
4891
4892 // We do not consume the motion right away, because that would require dispatcher to first
4893 // process (== drop) the key event, and by that time, ANR will be raised.
4894 // Set the focused window first.
4895 mFocusedWindow->setFocusable(true);
4896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4897 setFocusedWindow(mFocusedWindow);
4898 mFocusedWindow->consumeFocusEvent(true);
4899 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4900 // to another application. This could be a bug / behaviour in the policy.
4901
4902 mUnfocusedWindow->consumeMotionDown();
4903
4904 ASSERT_TRUE(mDispatcher->waitForIdle());
4905 // Should not ANR because we actually have a focused window. It was just added too slowly.
4906 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4907}
4908
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004909// These tests ensure we cannot send touch events to a window that's positioned behind a window
4910// that has feature NO_INPUT_CHANNEL.
4911// Layout:
4912// Top (closest to user)
4913// mNoInputWindow (above all windows)
4914// mBottomWindow
4915// Bottom (furthest from user)
4916class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4917 virtual void SetUp() override {
4918 InputDispatcherTest::SetUp();
4919
4920 mApplication = std::make_shared<FakeApplicationHandle>();
4921 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4922 "Window without input channel", ADISPLAY_ID_DEFAULT,
4923 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4924
chaviw3277faf2021-05-19 16:45:23 -05004925 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004926 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4927 // It's perfectly valid for this window to not have an associated input channel
4928
4929 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4930 ADISPLAY_ID_DEFAULT);
4931 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4932
4933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4934 }
4935
4936protected:
4937 std::shared_ptr<FakeApplicationHandle> mApplication;
4938 sp<FakeWindowHandle> mNoInputWindow;
4939 sp<FakeWindowHandle> mBottomWindow;
4940};
4941
4942TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4943 PointF touchedPoint = {10, 10};
4944
4945 NotifyMotionArgs motionArgs =
4946 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4947 ADISPLAY_ID_DEFAULT, {touchedPoint});
4948 mDispatcher->notifyMotion(&motionArgs);
4949
4950 mNoInputWindow->assertNoEvents();
4951 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4952 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4953 // and therefore should prevent mBottomWindow from receiving touches
4954 mBottomWindow->assertNoEvents();
4955}
4956
4957/**
4958 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4959 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4960 */
4961TEST_F(InputDispatcherMultiWindowOcclusionTests,
4962 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4963 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4964 "Window with input channel and NO_INPUT_CHANNEL",
4965 ADISPLAY_ID_DEFAULT);
4966
chaviw3277faf2021-05-19 16:45:23 -05004967 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004968 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4970
4971 PointF touchedPoint = {10, 10};
4972
4973 NotifyMotionArgs motionArgs =
4974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4975 ADISPLAY_ID_DEFAULT, {touchedPoint});
4976 mDispatcher->notifyMotion(&motionArgs);
4977
4978 mNoInputWindow->assertNoEvents();
4979 mBottomWindow->assertNoEvents();
4980}
4981
Vishnu Nair958da932020-08-21 17:12:37 -07004982class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4983protected:
4984 std::shared_ptr<FakeApplicationHandle> mApp;
4985 sp<FakeWindowHandle> mWindow;
4986 sp<FakeWindowHandle> mMirror;
4987
4988 virtual void SetUp() override {
4989 InputDispatcherTest::SetUp();
4990 mApp = std::make_shared<FakeApplicationHandle>();
4991 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4992 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4993 mWindow->getToken());
4994 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4995 mWindow->setFocusable(true);
4996 mMirror->setFocusable(true);
4997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4998 }
4999};
5000
5001TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5002 // Request focus on a mirrored window
5003 setFocusedWindow(mMirror);
5004
5005 // window gets focused
5006 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5008 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005009 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5010}
5011
5012// A focused & mirrored window remains focused only if the window and its mirror are both
5013// focusable.
5014TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5015 setFocusedWindow(mMirror);
5016
5017 // window gets focused
5018 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5020 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005021 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5023 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005024 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5025
5026 mMirror->setFocusable(false);
5027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5028
5029 // window loses focus since one of the windows associated with the token in not focusable
5030 mWindow->consumeFocusEvent(false);
5031
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005032 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5033 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005034 mWindow->assertNoEvents();
5035}
5036
5037// A focused & mirrored window remains focused until the window and its mirror both become
5038// invisible.
5039TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5040 setFocusedWindow(mMirror);
5041
5042 // window gets focused
5043 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5045 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005046 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5048 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005049 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5050
5051 mMirror->setVisible(false);
5052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5053
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5055 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005056 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5058 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005059 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5060
5061 mWindow->setVisible(false);
5062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5063
5064 // window loses focus only after all windows associated with the token become invisible.
5065 mWindow->consumeFocusEvent(false);
5066
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005067 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5068 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005069 mWindow->assertNoEvents();
5070}
5071
5072// A focused & mirrored window remains focused until both windows are removed.
5073TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5074 setFocusedWindow(mMirror);
5075
5076 // window gets focused
5077 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5079 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005080 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005081 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5082 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005083 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5084
5085 // single window is removed but the window token remains focused
5086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5087
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5089 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005090 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5092 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005093 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5094
5095 // Both windows are removed
5096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5097 mWindow->consumeFocusEvent(false);
5098
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005099 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5100 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005101 mWindow->assertNoEvents();
5102}
5103
5104// Focus request can be pending until one window becomes visible.
5105TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5106 // Request focus on an invisible mirror.
5107 mWindow->setVisible(false);
5108 mMirror->setVisible(false);
5109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5110 setFocusedWindow(mMirror);
5111
5112 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005114 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005115 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005116
5117 mMirror->setVisible(true);
5118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5119
5120 // window gets focused
5121 mWindow->consumeFocusEvent(true);
5122 // window gets the pending key event
5123 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5124}
Prabir Pradhan99987712020-11-10 18:43:05 -08005125
5126class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5127protected:
5128 std::shared_ptr<FakeApplicationHandle> mApp;
5129 sp<FakeWindowHandle> mWindow;
5130 sp<FakeWindowHandle> mSecondWindow;
5131
5132 void SetUp() override {
5133 InputDispatcherTest::SetUp();
5134 mApp = std::make_shared<FakeApplicationHandle>();
5135 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5136 mWindow->setFocusable(true);
5137 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5138 mSecondWindow->setFocusable(true);
5139
5140 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5142
5143 setFocusedWindow(mWindow);
5144 mWindow->consumeFocusEvent(true);
5145 }
5146
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005147 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5148 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005149 mDispatcher->notifyPointerCaptureChanged(&args);
5150 }
5151
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005152 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5153 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005154 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005155 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5156 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005157 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005158 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005159 }
5160};
5161
5162TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5163 // Ensure that capture cannot be obtained for unfocused windows.
5164 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5165 mFakePolicy->assertSetPointerCaptureNotCalled();
5166 mSecondWindow->assertNoEvents();
5167
5168 // Ensure that capture can be enabled from the focus window.
5169 requestAndVerifyPointerCapture(mWindow, true);
5170
5171 // Ensure that capture cannot be disabled from a window that does not have capture.
5172 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5173 mFakePolicy->assertSetPointerCaptureNotCalled();
5174
5175 // Ensure that capture can be disabled from the window with capture.
5176 requestAndVerifyPointerCapture(mWindow, false);
5177}
5178
5179TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005180 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005181
5182 setFocusedWindow(mSecondWindow);
5183
5184 // Ensure that the capture disabled event was sent first.
5185 mWindow->consumeCaptureEvent(false);
5186 mWindow->consumeFocusEvent(false);
5187 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005188 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005189
5190 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005191 notifyPointerCaptureChanged({});
5192 notifyPointerCaptureChanged(request);
5193 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005194 mWindow->assertNoEvents();
5195 mSecondWindow->assertNoEvents();
5196 mFakePolicy->assertSetPointerCaptureNotCalled();
5197}
5198
5199TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005200 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005201
5202 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005203 notifyPointerCaptureChanged({});
5204 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005205
5206 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005207 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005208 mWindow->consumeCaptureEvent(false);
5209 mWindow->assertNoEvents();
5210}
5211
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005212TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5213 requestAndVerifyPointerCapture(mWindow, true);
5214
5215 // The first window loses focus.
5216 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005217 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005218 mWindow->consumeCaptureEvent(false);
5219
5220 // Request Pointer Capture from the second window before the notification from InputReader
5221 // arrives.
5222 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005223 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005224
5225 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005226 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005227
5228 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005229 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005230
5231 mSecondWindow->consumeFocusEvent(true);
5232 mSecondWindow->consumeCaptureEvent(true);
5233}
5234
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005235TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5236 // App repeatedly enables and disables capture.
5237 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5238 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5239 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5240 mFakePolicy->assertSetPointerCaptureCalled(false);
5241 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5242 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5243
5244 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5245 // first request is now stale, this should do nothing.
5246 notifyPointerCaptureChanged(firstRequest);
5247 mWindow->assertNoEvents();
5248
5249 // InputReader notifies that the second request was enabled.
5250 notifyPointerCaptureChanged(secondRequest);
5251 mWindow->consumeCaptureEvent(true);
5252}
5253
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005254class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5255protected:
5256 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005257
5258 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5259 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5260
5261 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5262 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5263
5264 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5265 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5266 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5267 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5268 MAXIMUM_OBSCURING_OPACITY);
5269
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005270 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005271 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005272 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005273
5274 sp<FakeWindowHandle> mTouchWindow;
5275
5276 virtual void SetUp() override {
5277 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005278 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005279 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5280 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5281 }
5282
5283 virtual void TearDown() override {
5284 InputDispatcherTest::TearDown();
5285 mTouchWindow.clear();
5286 }
5287
chaviw3277faf2021-05-19 16:45:23 -05005288 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5289 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005290 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005291 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005292 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005293 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005294 return window;
5295 }
5296
5297 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5298 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5299 sp<FakeWindowHandle> window =
5300 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5301 // Generate an arbitrary PID based on the UID
5302 window->setOwnerInfo(1777 + (uid % 10000), uid);
5303 return window;
5304 }
5305
5306 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5307 NotifyMotionArgs args =
5308 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5309 ADISPLAY_ID_DEFAULT, points);
5310 mDispatcher->notifyMotion(&args);
5311 }
5312};
5313
5314TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005315 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005316 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005318
5319 touch();
5320
5321 mTouchWindow->assertNoEvents();
5322}
5323
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005324TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005325 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5326 const sp<FakeWindowHandle>& w =
5327 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5329
5330 touch();
5331
5332 mTouchWindow->assertNoEvents();
5333}
5334
5335TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005336 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5337 const sp<FakeWindowHandle>& w =
5338 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5340
5341 touch();
5342
5343 w->assertNoEvents();
5344}
5345
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005346TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005347 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005349
5350 touch();
5351
5352 mTouchWindow->consumeAnyMotionDown();
5353}
5354
5355TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005356 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005357 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005358 w->setFrame(Rect(0, 0, 50, 50));
5359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005360
5361 touch({PointF{100, 100}});
5362
5363 mTouchWindow->consumeAnyMotionDown();
5364}
5365
5366TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005367 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005368 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005369 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5370
5371 touch();
5372
5373 mTouchWindow->consumeAnyMotionDown();
5374}
5375
5376TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5377 const sp<FakeWindowHandle>& w =
5378 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005380
5381 touch();
5382
5383 mTouchWindow->consumeAnyMotionDown();
5384}
5385
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005386TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5387 const sp<FakeWindowHandle>& w =
5388 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5389 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5390
5391 touch();
5392
5393 w->assertNoEvents();
5394}
5395
5396/**
5397 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5398 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5399 * window, the occluding window will still receive ACTION_OUTSIDE event.
5400 */
5401TEST_F(InputDispatcherUntrustedTouchesTest,
5402 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5403 const sp<FakeWindowHandle>& w =
5404 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005405 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005406 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5407
5408 touch();
5409
5410 w->consumeMotionOutside();
5411}
5412
5413TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5414 const sp<FakeWindowHandle>& w =
5415 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005416 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5418
5419 touch();
5420
5421 InputEvent* event = w->consume();
5422 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5423 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5424 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5425 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5426}
5427
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005428TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005429 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005430 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5431 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5433
5434 touch();
5435
5436 mTouchWindow->consumeAnyMotionDown();
5437}
5438
5439TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5440 const sp<FakeWindowHandle>& w =
5441 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5442 MAXIMUM_OBSCURING_OPACITY);
5443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005444
5445 touch();
5446
5447 mTouchWindow->consumeAnyMotionDown();
5448}
5449
5450TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005451 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005452 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5453 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5455
5456 touch();
5457
5458 mTouchWindow->assertNoEvents();
5459}
5460
5461TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5462 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5463 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005464 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5465 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005466 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005467 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5468 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5470
5471 touch();
5472
5473 mTouchWindow->assertNoEvents();
5474}
5475
5476TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5477 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5478 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005479 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5480 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005481 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005482 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5483 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5485
5486 touch();
5487
5488 mTouchWindow->consumeAnyMotionDown();
5489}
5490
5491TEST_F(InputDispatcherUntrustedTouchesTest,
5492 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5493 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005494 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5495 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005496 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005497 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5498 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5500
5501 touch();
5502
5503 mTouchWindow->consumeAnyMotionDown();
5504}
5505
5506TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5507 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005508 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5509 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005510 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005511 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5512 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005514
5515 touch();
5516
5517 mTouchWindow->assertNoEvents();
5518}
5519
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005520TEST_F(InputDispatcherUntrustedTouchesTest,
5521 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5522 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005523 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5524 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005525 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005526 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5527 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5529
5530 touch();
5531
5532 mTouchWindow->assertNoEvents();
5533}
5534
5535TEST_F(InputDispatcherUntrustedTouchesTest,
5536 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5537 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005538 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5539 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005540 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005541 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5542 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5544
5545 touch();
5546
5547 mTouchWindow->consumeAnyMotionDown();
5548}
5549
5550TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5551 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005552 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5553 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5555
5556 touch();
5557
5558 mTouchWindow->consumeAnyMotionDown();
5559}
5560
5561TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5562 const sp<FakeWindowHandle>& w =
5563 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5565
5566 touch();
5567
5568 mTouchWindow->consumeAnyMotionDown();
5569}
5570
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005571TEST_F(InputDispatcherUntrustedTouchesTest,
5572 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5573 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5574 const sp<FakeWindowHandle>& w =
5575 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5577
5578 touch();
5579
5580 mTouchWindow->assertNoEvents();
5581}
5582
5583TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5584 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5585 const sp<FakeWindowHandle>& w =
5586 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5588
5589 touch();
5590
5591 mTouchWindow->consumeAnyMotionDown();
5592}
5593
5594TEST_F(InputDispatcherUntrustedTouchesTest,
5595 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5596 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5597 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005598 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5599 OPACITY_ABOVE_THRESHOLD);
5600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5601
5602 touch();
5603
5604 mTouchWindow->consumeAnyMotionDown();
5605}
5606
5607TEST_F(InputDispatcherUntrustedTouchesTest,
5608 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5609 const sp<FakeWindowHandle>& w1 =
5610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5611 OPACITY_BELOW_THRESHOLD);
5612 const sp<FakeWindowHandle>& w2 =
5613 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5614 OPACITY_BELOW_THRESHOLD);
5615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5616
5617 touch();
5618
5619 mTouchWindow->assertNoEvents();
5620}
5621
5622/**
5623 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5624 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5625 * (which alone would result in allowing touches) does not affect the blocking behavior.
5626 */
5627TEST_F(InputDispatcherUntrustedTouchesTest,
5628 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5629 const sp<FakeWindowHandle>& wB =
5630 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5631 OPACITY_BELOW_THRESHOLD);
5632 const sp<FakeWindowHandle>& wC =
5633 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5634 OPACITY_BELOW_THRESHOLD);
5635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5636
5637 touch();
5638
5639 mTouchWindow->assertNoEvents();
5640}
5641
5642/**
5643 * This test is testing that a window from a different UID but with same application token doesn't
5644 * block the touch. Apps can share the application token for close UI collaboration for example.
5645 */
5646TEST_F(InputDispatcherUntrustedTouchesTest,
5647 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5648 const sp<FakeWindowHandle>& w =
5649 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5650 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5652
5653 touch();
5654
5655 mTouchWindow->consumeAnyMotionDown();
5656}
5657
arthurhungb89ccb02020-12-30 16:19:01 +08005658class InputDispatcherDragTests : public InputDispatcherTest {
5659protected:
5660 std::shared_ptr<FakeApplicationHandle> mApp;
5661 sp<FakeWindowHandle> mWindow;
5662 sp<FakeWindowHandle> mSecondWindow;
5663 sp<FakeWindowHandle> mDragWindow;
5664
5665 void SetUp() override {
5666 InputDispatcherTest::SetUp();
5667 mApp = std::make_shared<FakeApplicationHandle>();
5668 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5669 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005670 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005671
5672 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5673 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005674 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005675
5676 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5678 }
5679
5680 // Start performing drag, we will create a drag window and transfer touch to it.
5681 void performDrag() {
5682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5683 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5684 {50, 50}))
5685 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5686
5687 // Window should receive motion event.
5688 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5689
5690 // The drag window covers the entire display
5691 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5692 mDispatcher->setInputWindows(
5693 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5694
5695 // Transfer touch focus to the drag window
5696 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5697 true /* isDragDrop */);
5698 mWindow->consumeMotionCancel();
5699 mDragWindow->consumeMotionDown();
5700 }
arthurhung6d4bed92021-03-17 11:59:33 +08005701
5702 // Start performing drag, we will create a drag window and transfer touch to it.
5703 void performStylusDrag() {
5704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5705 injectMotionEvent(mDispatcher,
5706 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5707 AINPUT_SOURCE_STYLUS)
5708 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5709 .pointer(PointerBuilder(0,
5710 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5711 .x(50)
5712 .y(50))
5713 .build()));
5714 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5715
5716 // The drag window covers the entire display
5717 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5718 mDispatcher->setInputWindows(
5719 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5720
5721 // Transfer touch focus to the drag window
5722 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5723 true /* isDragDrop */);
5724 mWindow->consumeMotionCancel();
5725 mDragWindow->consumeMotionDown();
5726 }
arthurhungb89ccb02020-12-30 16:19:01 +08005727};
5728
5729TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5730 performDrag();
5731
5732 // Move on window.
5733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5734 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5735 ADISPLAY_ID_DEFAULT, {50, 50}))
5736 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5737 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5738 mWindow->consumeDragEvent(false, 50, 50);
5739 mSecondWindow->assertNoEvents();
5740
5741 // Move to another window.
5742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5743 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5744 ADISPLAY_ID_DEFAULT, {150, 50}))
5745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5746 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5747 mWindow->consumeDragEvent(true, 150, 50);
5748 mSecondWindow->consumeDragEvent(false, 50, 50);
5749
5750 // Move back to original window.
5751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5752 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5753 ADISPLAY_ID_DEFAULT, {50, 50}))
5754 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5755 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5756 mWindow->consumeDragEvent(false, 50, 50);
5757 mSecondWindow->consumeDragEvent(true, -50, 50);
5758
5759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5760 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5761 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5762 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5763 mWindow->assertNoEvents();
5764 mSecondWindow->assertNoEvents();
5765}
5766
arthurhungf452d0b2021-01-06 00:19:52 +08005767TEST_F(InputDispatcherDragTests, DragAndDrop) {
5768 performDrag();
5769
5770 // Move on window.
5771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5772 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5773 ADISPLAY_ID_DEFAULT, {50, 50}))
5774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5775 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5776 mWindow->consumeDragEvent(false, 50, 50);
5777 mSecondWindow->assertNoEvents();
5778
5779 // Move to another window.
5780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5781 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5782 ADISPLAY_ID_DEFAULT, {150, 50}))
5783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5784 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5785 mWindow->consumeDragEvent(true, 150, 50);
5786 mSecondWindow->consumeDragEvent(false, 50, 50);
5787
5788 // drop to another window.
5789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5790 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5791 {150, 50}))
5792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5793 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5794 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5795 mWindow->assertNoEvents();
5796 mSecondWindow->assertNoEvents();
5797}
5798
arthurhung6d4bed92021-03-17 11:59:33 +08005799TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5800 performStylusDrag();
5801
5802 // Move on window and keep button pressed.
5803 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5804 injectMotionEvent(mDispatcher,
5805 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5806 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5807 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5808 .x(50)
5809 .y(50))
5810 .build()))
5811 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5812 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5813 mWindow->consumeDragEvent(false, 50, 50);
5814 mSecondWindow->assertNoEvents();
5815
5816 // Move to another window and release button, expect to drop item.
5817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5818 injectMotionEvent(mDispatcher,
5819 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5820 .buttonState(0)
5821 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5822 .x(150)
5823 .y(50))
5824 .build()))
5825 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5826 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5827 mWindow->assertNoEvents();
5828 mSecondWindow->assertNoEvents();
5829 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5830
5831 // nothing to the window.
5832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5833 injectMotionEvent(mDispatcher,
5834 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5835 .buttonState(0)
5836 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5837 .x(150)
5838 .y(50))
5839 .build()))
5840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5841 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5842 mWindow->assertNoEvents();
5843 mSecondWindow->assertNoEvents();
5844}
5845
Arthur Hung6d0571e2021-04-09 20:18:16 +08005846TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5847 performDrag();
5848
5849 // Set second window invisible.
5850 mSecondWindow->setVisible(false);
5851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5852
5853 // Move on window.
5854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5855 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5856 ADISPLAY_ID_DEFAULT, {50, 50}))
5857 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5858 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5859 mWindow->consumeDragEvent(false, 50, 50);
5860 mSecondWindow->assertNoEvents();
5861
5862 // Move to another window.
5863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5864 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5865 ADISPLAY_ID_DEFAULT, {150, 50}))
5866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5867 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5868 mWindow->consumeDragEvent(true, 150, 50);
5869 mSecondWindow->assertNoEvents();
5870
5871 // drop to another window.
5872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5873 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5874 {150, 50}))
5875 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5876 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5877 mFakePolicy->assertDropTargetEquals(nullptr);
5878 mWindow->assertNoEvents();
5879 mSecondWindow->assertNoEvents();
5880}
5881
Vishnu Nair062a8672021-09-03 16:07:44 -07005882class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5883
5884TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5885 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5886 sp<FakeWindowHandle> window =
5887 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5888 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5889 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5890 window->setFocusable(true);
5891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5892 setFocusedWindow(window);
5893 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5894
5895 // With the flag set, window should not get any input
5896 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5897 mDispatcher->notifyKey(&keyArgs);
5898 window->assertNoEvents();
5899
5900 NotifyMotionArgs motionArgs =
5901 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5902 ADISPLAY_ID_DEFAULT);
5903 mDispatcher->notifyMotion(&motionArgs);
5904 window->assertNoEvents();
5905
5906 // With the flag cleared, the window should get input
5907 window->setInputFeatures({});
5908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5909
5910 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5911 mDispatcher->notifyKey(&keyArgs);
5912 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5913
5914 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5915 ADISPLAY_ID_DEFAULT);
5916 mDispatcher->notifyMotion(&motionArgs);
5917 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5918 window->assertNoEvents();
5919}
5920
5921TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5922 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5923 std::make_shared<FakeApplicationHandle>();
5924 sp<FakeWindowHandle> obscuringWindow =
5925 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5926 ADISPLAY_ID_DEFAULT);
5927 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5928 obscuringWindow->setOwnerInfo(111, 111);
5929 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5930 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5931 sp<FakeWindowHandle> window =
5932 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5933 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5934 window->setOwnerInfo(222, 222);
5935 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5936 window->setFocusable(true);
5937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5938 setFocusedWindow(window);
5939 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5940
5941 // With the flag set, window should not get any input
5942 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5943 mDispatcher->notifyKey(&keyArgs);
5944 window->assertNoEvents();
5945
5946 NotifyMotionArgs motionArgs =
5947 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5948 ADISPLAY_ID_DEFAULT);
5949 mDispatcher->notifyMotion(&motionArgs);
5950 window->assertNoEvents();
5951
5952 // With the flag cleared, the window should get input
5953 window->setInputFeatures({});
5954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5955
5956 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5957 mDispatcher->notifyKey(&keyArgs);
5958 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5959
5960 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5961 ADISPLAY_ID_DEFAULT);
5962 mDispatcher->notifyMotion(&motionArgs);
5963 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5964 window->assertNoEvents();
5965}
5966
5967TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5968 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5969 std::make_shared<FakeApplicationHandle>();
5970 sp<FakeWindowHandle> obscuringWindow =
5971 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5972 ADISPLAY_ID_DEFAULT);
5973 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5974 obscuringWindow->setOwnerInfo(111, 111);
5975 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5976 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5977 sp<FakeWindowHandle> window =
5978 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5979 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5980 window->setOwnerInfo(222, 222);
5981 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5982 window->setFocusable(true);
5983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5984 setFocusedWindow(window);
5985 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5986
5987 // With the flag set, window should not get any input
5988 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5989 mDispatcher->notifyKey(&keyArgs);
5990 window->assertNoEvents();
5991
5992 NotifyMotionArgs motionArgs =
5993 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5994 ADISPLAY_ID_DEFAULT);
5995 mDispatcher->notifyMotion(&motionArgs);
5996 window->assertNoEvents();
5997
5998 // When the window is no longer obscured because it went on top, it should get input
5999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6000
6001 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6002 mDispatcher->notifyKey(&keyArgs);
6003 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6004
6005 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6006 ADISPLAY_ID_DEFAULT);
6007 mDispatcher->notifyMotion(&motionArgs);
6008 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6009 window->assertNoEvents();
6010}
6011
Antonio Kantekf16f2832021-09-28 04:39:20 +00006012class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6013protected:
6014 std::shared_ptr<FakeApplicationHandle> mApp;
6015 sp<FakeWindowHandle> mWindow;
6016 sp<FakeWindowHandle> mSecondWindow;
6017
6018 void SetUp() override {
6019 InputDispatcherTest::SetUp();
6020
6021 mApp = std::make_shared<FakeApplicationHandle>();
6022 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6023 mWindow->setFocusable(true);
6024 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6025 mSecondWindow->setFocusable(true);
6026
6027 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6029
6030 setFocusedWindow(mWindow);
6031 mWindow->consumeFocusEvent(true);
6032 }
6033
6034 void changeAndVerifyTouchMode(bool inTouchMode) {
6035 mDispatcher->setInTouchMode(inTouchMode);
6036 mWindow->consumeTouchModeEvent(inTouchMode);
6037 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6038 }
6039};
6040
6041TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6042 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6043}
6044
6045TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6046 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6047 mWindow->assertNoEvents();
6048 mSecondWindow->assertNoEvents();
6049}
6050
Garfield Tane84e6f92019-08-29 17:28:41 -07006051} // namespace android::inputdispatcher