blob: eaea4e26c4f3168488a3de953632d370678cc7a3 [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
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002082// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2083// event should be treated as being in the logical display space.
2084TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2085 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2086
2087 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2088 ui::Transform injectedEventTransform;
2089 injectedEventTransform.set(matrix);
2090 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2091 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2092
2093 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2094 .displayId(ADISPLAY_ID_DEFAULT)
2095 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2096 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2097 .x(untransformedPoint.x)
2098 .y(untransformedPoint.y))
2099 .build();
2100 event.transform(matrix);
2101
2102 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2103 InputEventInjectionSync::WAIT_FOR_RESULT);
2104
2105 firstWindow->consumeMotionDown();
2106 secondWindow->assertNoEvents();
2107}
2108
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002109TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2110 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2111
2112 // Send down to the second window.
2113 NotifyMotionArgs downMotionArgs =
2114 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2115 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2116 mDispatcher->notifyMotion(&downMotionArgs);
2117
2118 firstWindow->assertNoEvents();
2119 const MotionEvent* event = secondWindow->consumeMotion();
2120 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2121
2122 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2123 EXPECT_EQ(300, event->getRawX(0));
2124 EXPECT_EQ(880, event->getRawY(0));
2125
2126 // Ensure that the x and y values are in the window's coordinate space.
2127 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2128 // the logical display space. This will be the origin of the window space.
2129 EXPECT_EQ(100, event->getX(0));
2130 EXPECT_EQ(80, event->getY(0));
2131}
2132
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002133using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2134 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002135
2136class TransferTouchFixture : public InputDispatcherTest,
2137 public ::testing::WithParamInterface<TransferFunction> {};
2138
2139TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002140 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002141
2142 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002143 sp<FakeWindowHandle> firstWindow =
2144 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2145 sp<FakeWindowHandle> secondWindow =
2146 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002147
2148 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002150
2151 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002152 NotifyMotionArgs downMotionArgs =
2153 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2154 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002155 mDispatcher->notifyMotion(&downMotionArgs);
2156 // Only the first window should get the down event
2157 firstWindow->consumeMotionDown();
2158 secondWindow->assertNoEvents();
2159
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002160 // Transfer touch to the second window
2161 TransferFunction f = GetParam();
2162 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2163 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002164 // The first window gets cancel and the second gets down
2165 firstWindow->consumeMotionCancel();
2166 secondWindow->consumeMotionDown();
2167
2168 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002169 NotifyMotionArgs upMotionArgs =
2170 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2171 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002172 mDispatcher->notifyMotion(&upMotionArgs);
2173 // The first window gets no events and the second gets up
2174 firstWindow->assertNoEvents();
2175 secondWindow->consumeMotionUp();
2176}
2177
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002178TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002180
2181 PointF touchPoint = {10, 10};
2182
2183 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002184 sp<FakeWindowHandle> firstWindow =
2185 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2186 sp<FakeWindowHandle> secondWindow =
2187 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002188
2189 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002191
2192 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002193 NotifyMotionArgs downMotionArgs =
2194 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2195 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002196 mDispatcher->notifyMotion(&downMotionArgs);
2197 // Only the first window should get the down event
2198 firstWindow->consumeMotionDown();
2199 secondWindow->assertNoEvents();
2200
2201 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002202 NotifyMotionArgs pointerDownMotionArgs =
2203 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2204 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2205 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2206 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002207 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2208 // Only the first window should get the pointer down event
2209 firstWindow->consumeMotionPointerDown(1);
2210 secondWindow->assertNoEvents();
2211
2212 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002213 TransferFunction f = GetParam();
2214 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2215 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002216 // The first window gets cancel and the second gets down and pointer down
2217 firstWindow->consumeMotionCancel();
2218 secondWindow->consumeMotionDown();
2219 secondWindow->consumeMotionPointerDown(1);
2220
2221 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002222 NotifyMotionArgs pointerUpMotionArgs =
2223 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2224 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2225 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2226 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002227 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2228 // The first window gets nothing and the second gets pointer up
2229 firstWindow->assertNoEvents();
2230 secondWindow->consumeMotionPointerUp(1);
2231
2232 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002233 NotifyMotionArgs upMotionArgs =
2234 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2235 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002236 mDispatcher->notifyMotion(&upMotionArgs);
2237 // The first window gets nothing and the second gets up
2238 firstWindow->assertNoEvents();
2239 secondWindow->consumeMotionUp();
2240}
2241
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002242// For the cases of single pointer touch and two pointers non-split touch, the api's
2243// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2244// for the case where there are multiple pointers split across several windows.
2245INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2246 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002247 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2248 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002249 return dispatcher->transferTouch(destChannelToken);
2250 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002251 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2252 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002253 return dispatcher->transferTouchFocus(from, to,
2254 false /*isDragAndDrop*/);
2255 }));
2256
Svet Ganov5d3bc372020-01-26 23:11:07 -08002257TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002258 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002259
2260 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002261 sp<FakeWindowHandle> firstWindow =
2262 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002263 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002264 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002265
2266 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002267 sp<FakeWindowHandle> secondWindow =
2268 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002269 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002270 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002271
2272 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002274
2275 PointF pointInFirst = {300, 200};
2276 PointF pointInSecond = {300, 600};
2277
2278 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002279 NotifyMotionArgs firstDownMotionArgs =
2280 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2281 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002282 mDispatcher->notifyMotion(&firstDownMotionArgs);
2283 // Only the first window should get the down event
2284 firstWindow->consumeMotionDown();
2285 secondWindow->assertNoEvents();
2286
2287 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002288 NotifyMotionArgs secondDownMotionArgs =
2289 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2290 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2291 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2292 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002293 mDispatcher->notifyMotion(&secondDownMotionArgs);
2294 // The first window gets a move and the second a down
2295 firstWindow->consumeMotionMove();
2296 secondWindow->consumeMotionDown();
2297
2298 // Transfer touch focus to the second window
2299 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2300 // The first window gets cancel and the new gets pointer down (it already saw down)
2301 firstWindow->consumeMotionCancel();
2302 secondWindow->consumeMotionPointerDown(1);
2303
2304 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002305 NotifyMotionArgs pointerUpMotionArgs =
2306 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2307 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2308 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2309 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002310 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2311 // The first window gets nothing and the second gets pointer up
2312 firstWindow->assertNoEvents();
2313 secondWindow->consumeMotionPointerUp(1);
2314
2315 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002316 NotifyMotionArgs upMotionArgs =
2317 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2318 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002319 mDispatcher->notifyMotion(&upMotionArgs);
2320 // The first window gets nothing and the second gets up
2321 firstWindow->assertNoEvents();
2322 secondWindow->consumeMotionUp();
2323}
2324
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002325// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2326// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2327// touch is not supported, so the touch should continue on those windows and the transferred-to
2328// window should get nothing.
2329TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2330 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2331
2332 // Create a non touch modal window that supports split touch
2333 sp<FakeWindowHandle> firstWindow =
2334 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2335 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002336 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002337
2338 // Create a non touch modal window that supports split touch
2339 sp<FakeWindowHandle> secondWindow =
2340 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2341 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002342 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002343
2344 // Add the windows to the dispatcher
2345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2346
2347 PointF pointInFirst = {300, 200};
2348 PointF pointInSecond = {300, 600};
2349
2350 // Send down to the first window
2351 NotifyMotionArgs firstDownMotionArgs =
2352 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2353 ADISPLAY_ID_DEFAULT, {pointInFirst});
2354 mDispatcher->notifyMotion(&firstDownMotionArgs);
2355 // Only the first window should get the down event
2356 firstWindow->consumeMotionDown();
2357 secondWindow->assertNoEvents();
2358
2359 // Send down to the second window
2360 NotifyMotionArgs secondDownMotionArgs =
2361 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2362 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2363 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2364 {pointInFirst, pointInSecond});
2365 mDispatcher->notifyMotion(&secondDownMotionArgs);
2366 // The first window gets a move and the second a down
2367 firstWindow->consumeMotionMove();
2368 secondWindow->consumeMotionDown();
2369
2370 // Transfer touch focus to the second window
2371 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2372 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2373 ASSERT_FALSE(transferred);
2374 firstWindow->assertNoEvents();
2375 secondWindow->assertNoEvents();
2376
2377 // The rest of the dispatch should proceed as normal
2378 // Send pointer up to the second window
2379 NotifyMotionArgs pointerUpMotionArgs =
2380 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2381 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2382 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2383 {pointInFirst, pointInSecond});
2384 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2385 // The first window gets MOVE and the second gets pointer up
2386 firstWindow->consumeMotionMove();
2387 secondWindow->consumeMotionUp();
2388
2389 // Send up event to the first window
2390 NotifyMotionArgs upMotionArgs =
2391 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2392 ADISPLAY_ID_DEFAULT);
2393 mDispatcher->notifyMotion(&upMotionArgs);
2394 // The first window gets nothing and the second gets up
2395 firstWindow->consumeMotionUp();
2396 secondWindow->assertNoEvents();
2397}
2398
Arthur Hungabbb9d82021-09-01 14:52:30 +00002399// This case will create two windows and one mirrored window on the default display and mirror
2400// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2401// the windows info of second display before default display.
2402TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2404 sp<FakeWindowHandle> firstWindowInPrimary =
2405 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2406 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2407 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2408 sp<FakeWindowHandle> secondWindowInPrimary =
2409 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2410 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2411 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2412
2413 sp<FakeWindowHandle> mirrorWindowInPrimary =
2414 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2415 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2416 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2417
2418 sp<FakeWindowHandle> firstWindowInSecondary =
2419 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2420 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2421 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2422
2423 sp<FakeWindowHandle> secondWindowInSecondary =
2424 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2425 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2426 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2427
2428 // Update window info, let it find window handle of second display first.
2429 mDispatcher->setInputWindows(
2430 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2431 {ADISPLAY_ID_DEFAULT,
2432 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2433
2434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2435 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2436 {50, 50}))
2437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2438
2439 // Window should receive motion event.
2440 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2441
2442 // Transfer touch focus
2443 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2444 secondWindowInPrimary->getToken()));
2445 // The first window gets cancel.
2446 firstWindowInPrimary->consumeMotionCancel();
2447 secondWindowInPrimary->consumeMotionDown();
2448
2449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2450 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2451 ADISPLAY_ID_DEFAULT, {150, 50}))
2452 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2453 firstWindowInPrimary->assertNoEvents();
2454 secondWindowInPrimary->consumeMotionMove();
2455
2456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2457 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2458 {150, 50}))
2459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2460 firstWindowInPrimary->assertNoEvents();
2461 secondWindowInPrimary->consumeMotionUp();
2462}
2463
2464// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2465// 'transferTouch' api.
2466TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2467 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2468 sp<FakeWindowHandle> firstWindowInPrimary =
2469 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2470 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2471 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2472 sp<FakeWindowHandle> secondWindowInPrimary =
2473 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2474 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2475 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2476
2477 sp<FakeWindowHandle> mirrorWindowInPrimary =
2478 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2479 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2480 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2481
2482 sp<FakeWindowHandle> firstWindowInSecondary =
2483 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2484 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2485 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2486
2487 sp<FakeWindowHandle> secondWindowInSecondary =
2488 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2489 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2490 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2491
2492 // Update window info, let it find window handle of second display first.
2493 mDispatcher->setInputWindows(
2494 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2495 {ADISPLAY_ID_DEFAULT,
2496 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2497
2498 // Touch on second display.
2499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2501 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2502
2503 // Window should receive motion event.
2504 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2505
2506 // Transfer touch focus
2507 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2508
2509 // The first window gets cancel.
2510 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2511 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2512
2513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2514 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2515 SECOND_DISPLAY_ID, {150, 50}))
2516 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2517 firstWindowInPrimary->assertNoEvents();
2518 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2519
2520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2521 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2522 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2523 firstWindowInPrimary->assertNoEvents();
2524 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2525}
2526
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002527TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002528 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002529 sp<FakeWindowHandle> window =
2530 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2531
Vishnu Nair47074b82020-08-14 11:54:47 -07002532 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002534 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002535
2536 window->consumeFocusEvent(true);
2537
2538 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2539 mDispatcher->notifyKey(&keyArgs);
2540
2541 // Window should receive key down event.
2542 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2543}
2544
2545TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002546 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002547 sp<FakeWindowHandle> window =
2548 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2549
Arthur Hung72d8dc32020-03-28 00:48:39 +00002550 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002551
2552 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2553 mDispatcher->notifyKey(&keyArgs);
2554 mDispatcher->waitForIdle();
2555
2556 window->assertNoEvents();
2557}
2558
2559// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2560TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002561 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002562 sp<FakeWindowHandle> window =
2563 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2564
Arthur Hung72d8dc32020-03-28 00:48:39 +00002565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002566
2567 // Send key
2568 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2569 mDispatcher->notifyKey(&keyArgs);
2570 // Send motion
2571 NotifyMotionArgs motionArgs =
2572 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2573 ADISPLAY_ID_DEFAULT);
2574 mDispatcher->notifyMotion(&motionArgs);
2575
2576 // Window should receive only the motion event
2577 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2578 window->assertNoEvents(); // Key event or focus event will not be received
2579}
2580
arthurhungea3f4fc2020-12-21 23:18:53 +08002581TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2582 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2583
2584 // Create first non touch modal window that supports split touch
2585 sp<FakeWindowHandle> firstWindow =
2586 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2587 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002588 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002589
2590 // Create second non touch modal window that supports split touch
2591 sp<FakeWindowHandle> secondWindow =
2592 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2593 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002594 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002595
2596 // Add the windows to the dispatcher
2597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2598
2599 PointF pointInFirst = {300, 200};
2600 PointF pointInSecond = {300, 600};
2601
2602 // Send down to the first window
2603 NotifyMotionArgs firstDownMotionArgs =
2604 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2605 ADISPLAY_ID_DEFAULT, {pointInFirst});
2606 mDispatcher->notifyMotion(&firstDownMotionArgs);
2607 // Only the first window should get the down event
2608 firstWindow->consumeMotionDown();
2609 secondWindow->assertNoEvents();
2610
2611 // Send down to the second window
2612 NotifyMotionArgs secondDownMotionArgs =
2613 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2614 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2615 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2616 {pointInFirst, pointInSecond});
2617 mDispatcher->notifyMotion(&secondDownMotionArgs);
2618 // The first window gets a move and the second a down
2619 firstWindow->consumeMotionMove();
2620 secondWindow->consumeMotionDown();
2621
2622 // Send pointer cancel to the second window
2623 NotifyMotionArgs pointerUpMotionArgs =
2624 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2625 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2626 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2627 {pointInFirst, pointInSecond});
2628 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2629 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2630 // The first window gets move and the second gets cancel.
2631 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2632 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2633
2634 // Send up event.
2635 NotifyMotionArgs upMotionArgs =
2636 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2637 ADISPLAY_ID_DEFAULT);
2638 mDispatcher->notifyMotion(&upMotionArgs);
2639 // The first window gets up and the second gets nothing.
2640 firstWindow->consumeMotionUp();
2641 secondWindow->assertNoEvents();
2642}
2643
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002644TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2645 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2646
2647 sp<FakeWindowHandle> window =
2648 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2650 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2651 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2652 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2653
2654 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2655 window->assertNoEvents();
2656 mDispatcher->waitForIdle();
2657}
2658
chaviwd1c23182019-12-20 18:44:56 -08002659class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002660public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002661 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002662 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002663 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002664 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002665 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002666 }
2667
chaviwd1c23182019-12-20 18:44:56 -08002668 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2669
2670 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2671 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2672 expectedDisplayId, expectedFlags);
2673 }
2674
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002675 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2676
2677 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2678
chaviwd1c23182019-12-20 18:44:56 -08002679 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2680 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2681 expectedDisplayId, expectedFlags);
2682 }
2683
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002684 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2685 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2686 expectedDisplayId, expectedFlags);
2687 }
2688
chaviwd1c23182019-12-20 18:44:56 -08002689 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2690 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2691 expectedDisplayId, expectedFlags);
2692 }
2693
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002694 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2695 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2696 expectedDisplayId, expectedFlags);
2697 }
2698
Evan Rosky84f07f02021-04-16 10:42:42 -07002699 MotionEvent* consumeMotion() {
2700 InputEvent* event = mInputReceiver->consume();
2701 if (!event) {
2702 ADD_FAILURE() << "No event was produced";
2703 return nullptr;
2704 }
2705 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2706 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2707 return nullptr;
2708 }
2709 return static_cast<MotionEvent*>(event);
2710 }
2711
chaviwd1c23182019-12-20 18:44:56 -08002712 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2713
2714private:
2715 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002716};
2717
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002718/**
2719 * Two entities that receive touch: A window, and a global monitor.
2720 * The touch goes to the window, and then the window disappears.
2721 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2722 * for the monitor, as well.
2723 * 1. foregroundWindow
2724 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2725 */
2726TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2727 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2728 sp<FakeWindowHandle> window =
2729 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2730
2731 FakeMonitorReceiver monitor =
2732 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2733 false /*isGestureMonitor*/);
2734
2735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2738 {100, 200}))
2739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2740
2741 // Both the foreground window and the global monitor should receive the touch down
2742 window->consumeMotionDown();
2743 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2744
2745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2746 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2747 ADISPLAY_ID_DEFAULT, {110, 200}))
2748 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2749
2750 window->consumeMotionMove();
2751 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2752
2753 // Now the foreground window goes away
2754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2755 window->consumeMotionCancel();
2756 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2757
2758 // If more events come in, there will be no more foreground window to send them to. This will
2759 // cause a cancel for the monitor, as well.
2760 ASSERT_EQ(InputEventInjectionResult::FAILED,
2761 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2762 ADISPLAY_ID_DEFAULT, {120, 200}))
2763 << "Injection should fail because the window was removed";
2764 window->assertNoEvents();
2765 // Global monitor now gets the cancel
2766 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2767}
2768
Michael Wright3a240c42019-12-10 20:53:41 +00002769// Tests for gesture monitors
2770TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002771 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002772 sp<FakeWindowHandle> window =
2773 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002775
chaviwd1c23182019-12-20 18:44:56 -08002776 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2777 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002778
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002781 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002782 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002783 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002784}
2785
2786TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002787 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002788 sp<FakeWindowHandle> window =
2789 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2790
2791 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002792 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002793
Arthur Hung72d8dc32020-03-28 00:48:39 +00002794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002795 setFocusedWindow(window);
2796
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002797 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002798
chaviwd1c23182019-12-20 18:44:56 -08002799 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2800 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002801
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2803 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002804 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002805 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002806}
2807
2808TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002809 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002810 sp<FakeWindowHandle> window =
2811 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002813
chaviwd1c23182019-12-20 18:44:56 -08002814 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2815 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002816
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002818 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002819 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002820 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002821 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002822
2823 window->releaseChannel();
2824
chaviwd1c23182019-12-20 18:44:56 -08002825 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002826
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002827 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002828 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002829 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002830 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002831}
2832
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002833TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2834 FakeMonitorReceiver monitor =
2835 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2836 true /*isGestureMonitor*/);
2837
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002839 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2840 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2841 ASSERT_TRUE(consumeSeq);
2842
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002843 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002844 monitor.finishEvent(*consumeSeq);
2845 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002846 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002847}
2848
Evan Rosky84f07f02021-04-16 10:42:42 -07002849// Tests for gesture monitors
2850TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2851 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2852 sp<FakeWindowHandle> window =
2853 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2855 window->setWindowOffset(20, 40);
2856 window->setWindowTransform(0, 1, -1, 0);
2857
2858 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2859 true /*isGestureMonitor*/);
2860
2861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2863 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2864 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2865 MotionEvent* event = monitor.consumeMotion();
2866 // Even though window has transform, gesture monitor must not.
2867 ASSERT_EQ(ui::Transform(), event->getTransform());
2868}
2869
Arthur Hungb3307ee2021-10-14 10:57:37 +00002870TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2871 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2872 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2873 true /*isGestureMonitor*/);
2874
2875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2876 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2877 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2878 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2879}
2880
chaviw81e2bb92019-12-18 15:03:51 -08002881TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002882 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002883 sp<FakeWindowHandle> window =
2884 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2885
Arthur Hung72d8dc32020-03-28 00:48:39 +00002886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002887
2888 NotifyMotionArgs motionArgs =
2889 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2890 ADISPLAY_ID_DEFAULT);
2891
2892 mDispatcher->notifyMotion(&motionArgs);
2893 // Window should receive motion down event.
2894 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2895
2896 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002897 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002898 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2899 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2900 motionArgs.pointerCoords[0].getX() - 10);
2901
2902 mDispatcher->notifyMotion(&motionArgs);
2903 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2904 0 /*expectedFlags*/);
2905}
2906
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002907/**
2908 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2909 * the device default right away. In the test scenario, we check both the default value,
2910 * and the action of enabling / disabling.
2911 */
2912TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002914 sp<FakeWindowHandle> window =
2915 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2916
2917 // Set focused application.
2918 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002919 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002920
2921 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002923 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002924 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2925
2926 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002927 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002928 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002929 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2930
2931 SCOPED_TRACE("Disable touch mode");
2932 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002933 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002934 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002936 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002937 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2938
2939 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002940 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002942 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2943
2944 SCOPED_TRACE("Enable touch mode again");
2945 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002946 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002947 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002949 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002950 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2951
2952 window->assertNoEvents();
2953}
2954
Gang Wange9087892020-01-07 12:17:14 -05002955TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002957 sp<FakeWindowHandle> window =
2958 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2959
2960 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002961 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002962
Arthur Hung72d8dc32020-03-28 00:48:39 +00002963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002964 setFocusedWindow(window);
2965
Gang Wange9087892020-01-07 12:17:14 -05002966 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2967
2968 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2969 mDispatcher->notifyKey(&keyArgs);
2970
2971 InputEvent* event = window->consume();
2972 ASSERT_NE(event, nullptr);
2973
2974 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2975 ASSERT_NE(verified, nullptr);
2976 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2977
2978 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2979 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2980 ASSERT_EQ(keyArgs.source, verified->source);
2981 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2982
2983 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2984
2985 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2986 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002987 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2988 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2989 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2990 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2991 ASSERT_EQ(0, verifiedKey.repeatCount);
2992}
2993
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002994TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002996 sp<FakeWindowHandle> window =
2997 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2998
2999 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3000
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003001 ui::Transform transform;
3002 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3003
3004 gui::DisplayInfo displayInfo;
3005 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3006 displayInfo.transform = transform;
3007
3008 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003009
3010 NotifyMotionArgs motionArgs =
3011 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3012 ADISPLAY_ID_DEFAULT);
3013 mDispatcher->notifyMotion(&motionArgs);
3014
3015 InputEvent* event = window->consume();
3016 ASSERT_NE(event, nullptr);
3017
3018 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3019 ASSERT_NE(verified, nullptr);
3020 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3021
3022 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3023 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3024 EXPECT_EQ(motionArgs.source, verified->source);
3025 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3026
3027 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3028
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003029 const vec2 rawXY =
3030 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3031 motionArgs.pointerCoords[0].getXYValue());
3032 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3033 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003034 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3035 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3036 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3037 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3038 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3039}
3040
chaviw09c8d2d2020-08-24 15:48:26 -07003041/**
3042 * Ensure that separate calls to sign the same data are generating the same key.
3043 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3044 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3045 * tests.
3046 */
3047TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3048 KeyEvent event = getTestKeyEvent();
3049 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3050
3051 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3052 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3053 ASSERT_EQ(hmac1, hmac2);
3054}
3055
3056/**
3057 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3058 */
3059TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3060 KeyEvent event = getTestKeyEvent();
3061 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3062 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3063
3064 verifiedEvent.deviceId += 1;
3065 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3066
3067 verifiedEvent.source += 1;
3068 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3069
3070 verifiedEvent.eventTimeNanos += 1;
3071 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3072
3073 verifiedEvent.displayId += 1;
3074 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3075
3076 verifiedEvent.action += 1;
3077 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3078
3079 verifiedEvent.downTimeNanos += 1;
3080 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3081
3082 verifiedEvent.flags += 1;
3083 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3084
3085 verifiedEvent.keyCode += 1;
3086 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3087
3088 verifiedEvent.scanCode += 1;
3089 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3090
3091 verifiedEvent.metaState += 1;
3092 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3093
3094 verifiedEvent.repeatCount += 1;
3095 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3096}
3097
Vishnu Nair958da932020-08-21 17:12:37 -07003098TEST_F(InputDispatcherTest, SetFocusedWindow) {
3099 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3100 sp<FakeWindowHandle> windowTop =
3101 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3102 sp<FakeWindowHandle> windowSecond =
3103 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3104 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3105
3106 // Top window is also focusable but is not granted focus.
3107 windowTop->setFocusable(true);
3108 windowSecond->setFocusable(true);
3109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3110 setFocusedWindow(windowSecond);
3111
3112 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3114 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003115
3116 // Focused window should receive event.
3117 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3118 windowTop->assertNoEvents();
3119}
3120
3121TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3122 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3123 sp<FakeWindowHandle> window =
3124 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3125 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3126
3127 window->setFocusable(true);
3128 // Release channel for window is no longer valid.
3129 window->releaseChannel();
3130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3131 setFocusedWindow(window);
3132
3133 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003134 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3135 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003136
3137 // window channel is invalid, so it should not receive any input event.
3138 window->assertNoEvents();
3139}
3140
3141TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3142 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3143 sp<FakeWindowHandle> window =
3144 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3145 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3146
3147 // Window is not focusable.
3148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3149 setFocusedWindow(window);
3150
3151 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003152 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3153 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003154
3155 // window is invalid, so it should not receive any input event.
3156 window->assertNoEvents();
3157}
3158
3159TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3160 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3161 sp<FakeWindowHandle> windowTop =
3162 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3163 sp<FakeWindowHandle> windowSecond =
3164 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3165 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3166
3167 windowTop->setFocusable(true);
3168 windowSecond->setFocusable(true);
3169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3170 setFocusedWindow(windowTop);
3171 windowTop->consumeFocusEvent(true);
3172
3173 setFocusedWindow(windowSecond, windowTop);
3174 windowSecond->consumeFocusEvent(true);
3175 windowTop->consumeFocusEvent(false);
3176
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3178 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003179
3180 // Focused window should receive event.
3181 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3182}
3183
3184TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3185 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3186 sp<FakeWindowHandle> windowTop =
3187 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3188 sp<FakeWindowHandle> windowSecond =
3189 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3190 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3191
3192 windowTop->setFocusable(true);
3193 windowSecond->setFocusable(true);
3194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3195 setFocusedWindow(windowSecond, windowTop);
3196
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3198 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003199
3200 // Event should be dropped.
3201 windowTop->assertNoEvents();
3202 windowSecond->assertNoEvents();
3203}
3204
3205TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3206 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3207 sp<FakeWindowHandle> window =
3208 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3209 sp<FakeWindowHandle> previousFocusedWindow =
3210 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3211 ADISPLAY_ID_DEFAULT);
3212 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3213
3214 window->setFocusable(true);
3215 previousFocusedWindow->setFocusable(true);
3216 window->setVisible(false);
3217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3218 setFocusedWindow(previousFocusedWindow);
3219 previousFocusedWindow->consumeFocusEvent(true);
3220
3221 // Requesting focus on invisible window takes focus from currently focused window.
3222 setFocusedWindow(window);
3223 previousFocusedWindow->consumeFocusEvent(false);
3224
3225 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003227 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003228 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003229
3230 // Window does not get focus event or key down.
3231 window->assertNoEvents();
3232
3233 // Window becomes visible.
3234 window->setVisible(true);
3235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3236
3237 // Window receives focus event.
3238 window->consumeFocusEvent(true);
3239 // Focused window receives key down.
3240 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3241}
3242
Vishnu Nair599f1412021-06-21 10:39:58 -07003243TEST_F(InputDispatcherTest, DisplayRemoved) {
3244 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3245 sp<FakeWindowHandle> window =
3246 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3247 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3248
3249 // window is granted focus.
3250 window->setFocusable(true);
3251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3252 setFocusedWindow(window);
3253 window->consumeFocusEvent(true);
3254
3255 // When a display is removed window loses focus.
3256 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3257 window->consumeFocusEvent(false);
3258}
3259
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003260/**
3261 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3262 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3263 * of the 'slipperyEnterWindow'.
3264 *
3265 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3266 * a way so that the touched location is no longer covered by the top window.
3267 *
3268 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3269 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3270 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3271 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3272 * with ACTION_DOWN).
3273 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3274 * window moved itself away from the touched location and had Flag::SLIPPERY.
3275 *
3276 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3277 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3278 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3279 *
3280 * In this test, we ensure that the event received by the bottom window has
3281 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3282 */
3283TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3284 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3285 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3286
3287 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289
3290 sp<FakeWindowHandle> slipperyExitWindow =
3291 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003292 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003293 // Make sure this one overlaps the bottom window
3294 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3295 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3296 // one. Windows with the same owner are not considered to be occluding each other.
3297 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3298
3299 sp<FakeWindowHandle> slipperyEnterWindow =
3300 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3301 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3302
3303 mDispatcher->setInputWindows(
3304 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3305
3306 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3307 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3308 ADISPLAY_ID_DEFAULT, {{50, 50}});
3309 mDispatcher->notifyMotion(&args);
3310 slipperyExitWindow->consumeMotionDown();
3311 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3312 mDispatcher->setInputWindows(
3313 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3314
3315 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3316 ADISPLAY_ID_DEFAULT, {{51, 51}});
3317 mDispatcher->notifyMotion(&args);
3318
3319 slipperyExitWindow->consumeMotionCancel();
3320
3321 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3322 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3323}
3324
Garfield Tan1c7bc862020-01-28 13:24:04 -08003325class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3326protected:
3327 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3328 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3329
Chris Yea209fde2020-07-22 13:54:51 -07003330 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003331 sp<FakeWindowHandle> mWindow;
3332
3333 virtual void SetUp() override {
3334 mFakePolicy = new FakeInputDispatcherPolicy();
3335 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003336 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003337 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3338 ASSERT_EQ(OK, mDispatcher->start());
3339
3340 setUpWindow();
3341 }
3342
3343 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003344 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003345 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3346
Vishnu Nair47074b82020-08-14 11:54:47 -07003347 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003349 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003350 mWindow->consumeFocusEvent(true);
3351 }
3352
Chris Ye2ad95392020-09-01 13:44:44 -07003353 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003354 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003355 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003356 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3357 mDispatcher->notifyKey(&keyArgs);
3358
3359 // Window should receive key down event.
3360 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3361 }
3362
3363 void expectKeyRepeatOnce(int32_t repeatCount) {
3364 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3365 InputEvent* repeatEvent = mWindow->consume();
3366 ASSERT_NE(nullptr, repeatEvent);
3367
3368 uint32_t eventType = repeatEvent->getType();
3369 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3370
3371 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3372 uint32_t eventAction = repeatKeyEvent->getAction();
3373 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3374 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3375 }
3376
Chris Ye2ad95392020-09-01 13:44:44 -07003377 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003378 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003379 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003380 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3381 mDispatcher->notifyKey(&keyArgs);
3382
3383 // Window should receive key down event.
3384 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3385 0 /*expectedFlags*/);
3386 }
3387};
3388
3389TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003390 sendAndConsumeKeyDown(1 /* deviceId */);
3391 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3392 expectKeyRepeatOnce(repeatCount);
3393 }
3394}
3395
3396TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3397 sendAndConsumeKeyDown(1 /* deviceId */);
3398 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3399 expectKeyRepeatOnce(repeatCount);
3400 }
3401 sendAndConsumeKeyDown(2 /* deviceId */);
3402 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003403 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3404 expectKeyRepeatOnce(repeatCount);
3405 }
3406}
3407
3408TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003409 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003410 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003411 sendAndConsumeKeyUp(1 /* deviceId */);
3412 mWindow->assertNoEvents();
3413}
3414
3415TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3416 sendAndConsumeKeyDown(1 /* deviceId */);
3417 expectKeyRepeatOnce(1 /*repeatCount*/);
3418 sendAndConsumeKeyDown(2 /* deviceId */);
3419 expectKeyRepeatOnce(1 /*repeatCount*/);
3420 // Stale key up from device 1.
3421 sendAndConsumeKeyUp(1 /* deviceId */);
3422 // Device 2 is still down, keep repeating
3423 expectKeyRepeatOnce(2 /*repeatCount*/);
3424 expectKeyRepeatOnce(3 /*repeatCount*/);
3425 // Device 2 key up
3426 sendAndConsumeKeyUp(2 /* deviceId */);
3427 mWindow->assertNoEvents();
3428}
3429
3430TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3431 sendAndConsumeKeyDown(1 /* deviceId */);
3432 expectKeyRepeatOnce(1 /*repeatCount*/);
3433 sendAndConsumeKeyDown(2 /* deviceId */);
3434 expectKeyRepeatOnce(1 /*repeatCount*/);
3435 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3436 sendAndConsumeKeyUp(2 /* deviceId */);
3437 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003438 mWindow->assertNoEvents();
3439}
3440
liushenxiang42232912021-05-21 20:24:09 +08003441TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3442 sendAndConsumeKeyDown(DEVICE_ID);
3443 expectKeyRepeatOnce(1 /*repeatCount*/);
3444 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3445 mDispatcher->notifyDeviceReset(&args);
3446 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3447 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3448 mWindow->assertNoEvents();
3449}
3450
Garfield Tan1c7bc862020-01-28 13:24:04 -08003451TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003452 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003453 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3454 InputEvent* repeatEvent = mWindow->consume();
3455 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3456 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3457 IdGenerator::getSource(repeatEvent->getId()));
3458 }
3459}
3460
3461TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003462 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003463
3464 std::unordered_set<int32_t> idSet;
3465 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3466 InputEvent* repeatEvent = mWindow->consume();
3467 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3468 int32_t id = repeatEvent->getId();
3469 EXPECT_EQ(idSet.end(), idSet.find(id));
3470 idSet.insert(id);
3471 }
3472}
3473
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003474/* Test InputDispatcher for MultiDisplay */
3475class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3476public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003477 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003478 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003479
Chris Yea209fde2020-07-22 13:54:51 -07003480 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003481 windowInPrimary =
3482 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003483
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003484 // Set focus window for primary display, but focused display would be second one.
3485 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003486 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003487 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003488 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003489 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003490
Chris Yea209fde2020-07-22 13:54:51 -07003491 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003492 windowInSecondary =
3493 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003494 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003495 // Set focus display to second one.
3496 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3497 // Set focus window for second display.
3498 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003499 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003500 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003501 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003502 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003503 }
3504
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003505 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003506 InputDispatcherTest::TearDown();
3507
Chris Yea209fde2020-07-22 13:54:51 -07003508 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003509 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003510 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003511 windowInSecondary.clear();
3512 }
3513
3514protected:
Chris Yea209fde2020-07-22 13:54:51 -07003515 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003516 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003517 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003518 sp<FakeWindowHandle> windowInSecondary;
3519};
3520
3521TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3522 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3524 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3525 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003526 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003527 windowInSecondary->assertNoEvents();
3528
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003529 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3531 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003533 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003534 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003535}
3536
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003537TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003538 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3540 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003541 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003542 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003543 windowInSecondary->assertNoEvents();
3544
3545 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003547 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003548 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003549 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003550
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003551 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003552 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003553
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003554 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003555 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3556 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003557
3558 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003559 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003560 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003561 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003562 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003563 windowInSecondary->assertNoEvents();
3564}
3565
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003566// Test per-display input monitors for motion event.
3567TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003568 FakeMonitorReceiver monitorInPrimary =
3569 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3570 FakeMonitorReceiver monitorInSecondary =
3571 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003572
3573 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3575 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003577 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003578 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003580 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581
3582 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003586 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003587 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003588 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003589 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590
3591 // Test inject a non-pointer motion event.
3592 // If specific a display, it will dispatch to the focused window of particular display,
3593 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3596 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003598 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003599 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003600 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003601}
3602
3603// Test per-display input monitors for key event.
3604TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003605 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003606 FakeMonitorReceiver monitorInPrimary =
3607 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3608 FakeMonitorReceiver monitorInSecondary =
3609 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003610
3611 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003612 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3613 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003614 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003615 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003616 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003617 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003618}
3619
Vishnu Nair958da932020-08-21 17:12:37 -07003620TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3621 sp<FakeWindowHandle> secondWindowInPrimary =
3622 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3623 secondWindowInPrimary->setFocusable(true);
3624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3625 setFocusedWindow(secondWindowInPrimary);
3626 windowInPrimary->consumeFocusEvent(false);
3627 secondWindowInPrimary->consumeFocusEvent(true);
3628
3629 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3631 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003632 windowInPrimary->assertNoEvents();
3633 windowInSecondary->assertNoEvents();
3634 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3635}
3636
Jackal Guof9696682018-10-05 12:23:23 +08003637class InputFilterTest : public InputDispatcherTest {
3638protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003639 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3640 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003641 NotifyMotionArgs motionArgs;
3642
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003643 motionArgs =
3644 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003645 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003646 motionArgs =
3647 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003648 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003649 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003650 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003651 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3652 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003653 } else {
3654 mFakePolicy->assertFilterInputEventWasNotCalled();
3655 }
3656 }
3657
3658 void testNotifyKey(bool expectToBeFiltered) {
3659 NotifyKeyArgs keyArgs;
3660
3661 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3662 mDispatcher->notifyKey(&keyArgs);
3663 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3664 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003665 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003666
3667 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003668 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003669 } else {
3670 mFakePolicy->assertFilterInputEventWasNotCalled();
3671 }
3672 }
3673};
3674
3675// Test InputFilter for MotionEvent
3676TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3677 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3678 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3679 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3680
3681 // Enable InputFilter
3682 mDispatcher->setInputFilterEnabled(true);
3683 // Test touch on both primary and second display, and check if both events are filtered.
3684 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3685 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3686
3687 // Disable InputFilter
3688 mDispatcher->setInputFilterEnabled(false);
3689 // Test touch on both primary and second display, and check if both events aren't filtered.
3690 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3691 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3692}
3693
3694// Test InputFilter for KeyEvent
3695TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3696 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3697 testNotifyKey(/*expectToBeFiltered*/ false);
3698
3699 // Enable InputFilter
3700 mDispatcher->setInputFilterEnabled(true);
3701 // Send a key event, and check if it is filtered.
3702 testNotifyKey(/*expectToBeFiltered*/ true);
3703
3704 // Disable InputFilter
3705 mDispatcher->setInputFilterEnabled(false);
3706 // Send a key event, and check if it isn't filtered.
3707 testNotifyKey(/*expectToBeFiltered*/ false);
3708}
3709
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003710// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3711// logical display coordinate space.
3712TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3713 ui::Transform firstDisplayTransform;
3714 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3715 ui::Transform secondDisplayTransform;
3716 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3717
3718 std::vector<gui::DisplayInfo> displayInfos(2);
3719 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3720 displayInfos[0].transform = firstDisplayTransform;
3721 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3722 displayInfos[1].transform = secondDisplayTransform;
3723
3724 mDispatcher->onWindowInfosChanged({}, displayInfos);
3725
3726 // Enable InputFilter
3727 mDispatcher->setInputFilterEnabled(true);
3728
3729 // Ensure the correct transforms are used for the displays.
3730 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3731 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3732}
3733
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003734class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3735protected:
3736 virtual void SetUp() override {
3737 InputDispatcherTest::SetUp();
3738
3739 /**
3740 * We don't need to enable input filter to test the injected event policy, but we enabled it
3741 * here to make the tests more realistic, since this policy only matters when inputfilter is
3742 * on.
3743 */
3744 mDispatcher->setInputFilterEnabled(true);
3745
3746 std::shared_ptr<InputApplicationHandle> application =
3747 std::make_shared<FakeApplicationHandle>();
3748 mWindow =
3749 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3750
3751 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3752 mWindow->setFocusable(true);
3753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3754 setFocusedWindow(mWindow);
3755 mWindow->consumeFocusEvent(true);
3756 }
3757
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003758 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3759 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003760 KeyEvent event;
3761
3762 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3763 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3764 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3765 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3766 const int32_t additionalPolicyFlags =
3767 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3769 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3770 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3771 policyFlags | additionalPolicyFlags));
3772
3773 InputEvent* received = mWindow->consume();
3774 ASSERT_NE(nullptr, received);
3775 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003776 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3777 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3778 ASSERT_EQ(flags, keyEvent.getFlags());
3779 }
3780
3781 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3782 int32_t flags) {
3783 MotionEvent event;
3784 PointerProperties pointerProperties[1];
3785 PointerCoords pointerCoords[1];
3786 pointerProperties[0].clear();
3787 pointerProperties[0].id = 0;
3788 pointerCoords[0].clear();
3789 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3790 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3791
3792 ui::Transform identityTransform;
3793 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3794 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3795 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3796 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3797 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003798 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003799 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003800 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3801
3802 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3803 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3804 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3805 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3806 policyFlags | additionalPolicyFlags));
3807
3808 InputEvent* received = mWindow->consume();
3809 ASSERT_NE(nullptr, received);
3810 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3811 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3812 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3813 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003814 }
3815
3816private:
3817 sp<FakeWindowHandle> mWindow;
3818};
3819
3820TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003821 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3822 // filter. Without it, the event will no different from a regularly injected event, and the
3823 // injected device id will be overwritten.
3824 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3825 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003826}
3827
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003828TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003829 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003830 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3831 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3832}
3833
3834TEST_F(InputFilterInjectionPolicyTest,
3835 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3836 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3837 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3838 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003839}
3840
3841TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3842 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003843 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003844}
3845
chaviwfd6d3512019-03-25 13:23:49 -07003846class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003847 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003848 InputDispatcherTest::SetUp();
3849
Chris Yea209fde2020-07-22 13:54:51 -07003850 std::shared_ptr<FakeApplicationHandle> application =
3851 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003852 mUnfocusedWindow =
3853 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003854 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3855 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3856 // window.
chaviw3277faf2021-05-19 16:45:23 -05003857 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003858
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003859 mFocusedWindow =
3860 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3861 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003862 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003863
3864 // Set focused application.
3865 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003866 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003867
3868 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003870 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003871 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003872 }
3873
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003874 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003875 InputDispatcherTest::TearDown();
3876
3877 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003878 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003879 }
3880
3881protected:
3882 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003883 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003884 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003885};
3886
3887// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3888// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3889// the onPointerDownOutsideFocus callback.
3890TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003892 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3893 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003894 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003895 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003896
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003897 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003898 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3899}
3900
3901// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3902// DOWN on the window that doesn't have focus. Ensure no window received the
3903// onPointerDownOutsideFocus callback.
3904TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003908 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003909
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003910 ASSERT_TRUE(mDispatcher->waitForIdle());
3911 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003912}
3913
3914// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3915// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3916TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3918 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003919 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003920 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003921
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003922 ASSERT_TRUE(mDispatcher->waitForIdle());
3923 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003924}
3925
3926// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3927// DOWN on the window that already has focus. Ensure no window received the
3928// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003929TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003931 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003932 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003934 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003935
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003936 ASSERT_TRUE(mDispatcher->waitForIdle());
3937 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003938}
3939
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003940// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3941// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3942TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3943 const MotionEvent event =
3944 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3945 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3946 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3947 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3948 .build();
3949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3951 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3952
3953 ASSERT_TRUE(mDispatcher->waitForIdle());
3954 mFakePolicy->assertOnPointerDownWasNotCalled();
3955 // Ensure that the unfocused window did not receive any FOCUS events.
3956 mUnfocusedWindow->assertNoEvents();
3957}
3958
chaviwaf87b3e2019-10-01 16:59:28 -07003959// These tests ensures we can send touch events to a single client when there are multiple input
3960// windows that point to the same client token.
3961class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3962 virtual void SetUp() override {
3963 InputDispatcherTest::SetUp();
3964
Chris Yea209fde2020-07-22 13:54:51 -07003965 std::shared_ptr<FakeApplicationHandle> application =
3966 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003967 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3968 ADISPLAY_ID_DEFAULT);
3969 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3970 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003971 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003972 mWindow1->setFrame(Rect(0, 0, 100, 100));
3973
3974 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3975 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003976 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003977 mWindow2->setFrame(Rect(100, 100, 200, 200));
3978
Arthur Hung72d8dc32020-03-28 00:48:39 +00003979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003980 }
3981
3982protected:
3983 sp<FakeWindowHandle> mWindow1;
3984 sp<FakeWindowHandle> mWindow2;
3985
3986 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003987 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003988 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3989 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003990 }
3991
3992 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3993 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003994 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003995 InputEvent* event = window->consume();
3996
3997 ASSERT_NE(nullptr, event) << name.c_str()
3998 << ": consumer should have returned non-NULL event.";
3999
4000 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4001 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4002 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4003
4004 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004005 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004006
4007 for (size_t i = 0; i < points.size(); i++) {
4008 float expectedX = points[i].x;
4009 float expectedY = points[i].y;
4010
4011 EXPECT_EQ(expectedX, motionEvent.getX(i))
4012 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4013 << ", got " << motionEvent.getX(i);
4014 EXPECT_EQ(expectedY, motionEvent.getY(i))
4015 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4016 << ", got " << motionEvent.getY(i);
4017 }
4018 }
chaviw9eaa22c2020-07-01 16:21:27 -07004019
4020 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4021 std::vector<PointF> expectedPoints) {
4022 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4023 ADISPLAY_ID_DEFAULT, touchedPoints);
4024 mDispatcher->notifyMotion(&motionArgs);
4025
4026 // Always consume from window1 since it's the window that has the InputReceiver
4027 consumeMotionEvent(mWindow1, action, expectedPoints);
4028 }
chaviwaf87b3e2019-10-01 16:59:28 -07004029};
4030
4031TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4032 // Touch Window 1
4033 PointF touchedPoint = {10, 10};
4034 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004035 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004036
4037 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004038 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004039
4040 // Touch Window 2
4041 touchedPoint = {150, 150};
4042 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004043 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004044}
4045
chaviw9eaa22c2020-07-01 16:21:27 -07004046TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4047 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004048 mWindow2->setWindowScale(0.5f, 0.5f);
4049
4050 // Touch Window 1
4051 PointF touchedPoint = {10, 10};
4052 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004053 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004054 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004055 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004056
4057 // Touch Window 2
4058 touchedPoint = {150, 150};
4059 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004060 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4061 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004062
chaviw9eaa22c2020-07-01 16:21:27 -07004063 // Update the transform so rotation is set
4064 mWindow2->setWindowTransform(0, -1, 1, 0);
4065 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4066 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004067}
4068
chaviw9eaa22c2020-07-01 16:21:27 -07004069TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
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]));
4082 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004083
chaviw9eaa22c2020-07-01 16:21:27 -07004084 // Release Window 2
4085 int32_t actionPointerUp =
4086 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4087 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4088 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004089
chaviw9eaa22c2020-07-01 16:21:27 -07004090 // Update the transform so rotation is set for Window 2
4091 mWindow2->setWindowTransform(0, -1, 1, 0);
4092 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4093 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004094}
4095
chaviw9eaa22c2020-07-01 16:21:27 -07004096TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004097 mWindow2->setWindowScale(0.5f, 0.5f);
4098
4099 // Touch Window 1
4100 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4101 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004102 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004103
4104 // Touch Window 2
4105 int32_t actionPointerDown =
4106 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004107 touchedPoints.push_back(PointF{150, 150});
4108 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004109
chaviw9eaa22c2020-07-01 16:21:27 -07004110 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004111
4112 // Move both windows
4113 touchedPoints = {{20, 20}, {175, 175}};
4114 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4115 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4116
chaviw9eaa22c2020-07-01 16:21:27 -07004117 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004118
chaviw9eaa22c2020-07-01 16:21:27 -07004119 // Release Window 2
4120 int32_t actionPointerUp =
4121 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4122 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4123 expectedPoints.pop_back();
4124
4125 // Touch Window 2
4126 mWindow2->setWindowTransform(0, -1, 1, 0);
4127 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4128 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4129
4130 // Move both windows
4131 touchedPoints = {{20, 20}, {175, 175}};
4132 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4133 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4134
4135 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004136}
4137
4138TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4139 mWindow1->setWindowScale(0.5f, 0.5f);
4140
4141 // Touch Window 1
4142 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4143 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004144 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004145
4146 // Touch Window 2
4147 int32_t actionPointerDown =
4148 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004149 touchedPoints.push_back(PointF{150, 150});
4150 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004151
chaviw9eaa22c2020-07-01 16:21:27 -07004152 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004153
4154 // Move both windows
4155 touchedPoints = {{20, 20}, {175, 175}};
4156 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4157 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4158
chaviw9eaa22c2020-07-01 16:21:27 -07004159 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004160}
4161
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004162class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4163 virtual void SetUp() override {
4164 InputDispatcherTest::SetUp();
4165
Chris Yea209fde2020-07-22 13:54:51 -07004166 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004167 mApplication->setDispatchingTimeout(20ms);
4168 mWindow =
4169 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4170 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004171 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004172 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004173 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4174 // window.
chaviw3277faf2021-05-19 16:45:23 -05004175 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004176
4177 // Set focused application.
4178 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4179
4180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004181 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004182 mWindow->consumeFocusEvent(true);
4183 }
4184
4185 virtual void TearDown() override {
4186 InputDispatcherTest::TearDown();
4187 mWindow.clear();
4188 }
4189
4190protected:
Chris Yea209fde2020-07-22 13:54:51 -07004191 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004192 sp<FakeWindowHandle> mWindow;
4193 static constexpr PointF WINDOW_LOCATION = {20, 20};
4194
4195 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004197 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4198 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004200 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4201 WINDOW_LOCATION));
4202 }
4203};
4204
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004205// Send a tap and respond, which should not cause an ANR.
4206TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4207 tapOnWindow();
4208 mWindow->consumeMotionDown();
4209 mWindow->consumeMotionUp();
4210 ASSERT_TRUE(mDispatcher->waitForIdle());
4211 mFakePolicy->assertNotifyAnrWasNotCalled();
4212}
4213
4214// Send a regular key and respond, which should not cause an ANR.
4215TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004216 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004217 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4218 ASSERT_TRUE(mDispatcher->waitForIdle());
4219 mFakePolicy->assertNotifyAnrWasNotCalled();
4220}
4221
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004222TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4223 mWindow->setFocusable(false);
4224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4225 mWindow->consumeFocusEvent(false);
4226
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004227 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004228 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004229 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4230 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004232 // Key will not go to window because we have no focused window.
4233 // The 'no focused window' ANR timer should start instead.
4234
4235 // Now, the focused application goes away.
4236 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4237 // The key should get dropped and there should be no ANR.
4238
4239 ASSERT_TRUE(mDispatcher->waitForIdle());
4240 mFakePolicy->assertNotifyAnrWasNotCalled();
4241}
4242
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004243// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004244// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4245// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004246TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004248 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4249 WINDOW_LOCATION));
4250
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004251 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4252 ASSERT_TRUE(sequenceNum);
4253 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004254 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004255
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004256 mWindow->finishEvent(*sequenceNum);
4257 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4258 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004260 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004261}
4262
4263// Send a key to the app and have the app not respond right away.
4264TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4265 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004267 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4268 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004269 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004270 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004271 ASSERT_TRUE(mDispatcher->waitForIdle());
4272}
4273
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004274// We have a focused application, but no focused window
4275TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
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);
4279
4280 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004282 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4283 WINDOW_LOCATION));
4284 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4285 mDispatcher->waitForIdle();
4286 mFakePolicy->assertNotifyAnrWasNotCalled();
4287
4288 // Once a focused event arrives, we get an ANR for this application
4289 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4290 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004292 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004293 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004295 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004296 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004297 ASSERT_TRUE(mDispatcher->waitForIdle());
4298}
4299
4300// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004301// Make sure that we don't notify policy twice about the same ANR.
4302TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004303 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4305 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004306
4307 // Once a focused event arrives, we get an ANR for this application
4308 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4309 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004311 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004312 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004313 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004314 const std::chrono::duration appTimeout =
4315 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004316 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004317
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004318 std::this_thread::sleep_for(appTimeout);
4319 // ANR should not be raised again. It is up to policy to do that if it desires.
4320 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004321
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004322 // If we now get a focused window, the ANR should stop, but the policy handles that via
4323 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004324 ASSERT_TRUE(mDispatcher->waitForIdle());
4325}
4326
4327// We have a focused application, but no focused window
4328TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004329 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4331 mWindow->consumeFocusEvent(false);
4332
4333 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004334 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004335 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4337 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004338
4339 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004340 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004341
4342 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004343 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344 ASSERT_TRUE(mDispatcher->waitForIdle());
4345 mWindow->assertNoEvents();
4346}
4347
4348/**
4349 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4350 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4351 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4352 * the ANR mechanism should still work.
4353 *
4354 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4355 * DOWN event, while not responding on the second one.
4356 */
4357TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4358 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4359 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4360 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4361 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4362 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004364
4365 // Now send ACTION_UP, with identical timestamp
4366 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4367 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4368 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4369 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004371
4372 // We have now sent down and up. Let's consume first event and then ANR on the second.
4373 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4374 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004375 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004376}
4377
4378// If an app is not responding to a key event, gesture monitors should continue to receive
4379// new motion events
4380TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4381 FakeMonitorReceiver monitor =
4382 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4383 true /*isGestureMonitor*/);
4384
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4386 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004389
4390 // Stuck on the ACTION_UP
4391 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004392 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004393
4394 // New tap will go to the gesture monitor, but not to the window
4395 tapOnWindow();
4396 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4397 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4398
4399 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4400 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004401 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004402 mWindow->assertNoEvents();
4403 monitor.assertNoEvents();
4404}
4405
4406// If an app is not responding to a motion event, gesture monitors should continue to receive
4407// new motion events
4408TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4409 FakeMonitorReceiver monitor =
4410 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4411 true /*isGestureMonitor*/);
4412
4413 tapOnWindow();
4414 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4415 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4416
4417 mWindow->consumeMotionDown();
4418 // Stuck on the ACTION_UP
4419 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004420 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004421
4422 // New tap will go to the gesture monitor, but not to the window
4423 tapOnWindow();
4424 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4425 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4426
4427 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4428 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004429 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430 mWindow->assertNoEvents();
4431 monitor.assertNoEvents();
4432}
4433
4434// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4435// process events, you don't get an anr. When the window later becomes unresponsive again, you
4436// get an ANR again.
4437// 1. tap -> block on ACTION_UP -> receive ANR
4438// 2. consume all pending events (= queue becomes healthy again)
4439// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4440TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4441 tapOnWindow();
4442
4443 mWindow->consumeMotionDown();
4444 // Block on ACTION_UP
4445 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004446 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4448 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004449 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004450 mWindow->assertNoEvents();
4451
4452 tapOnWindow();
4453 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004454 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455 mWindow->consumeMotionUp();
4456
4457 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004458 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004459 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460 mWindow->assertNoEvents();
4461}
4462
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004463// If a connection remains unresponsive for a while, make sure policy is only notified once about
4464// it.
4465TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004467 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4468 WINDOW_LOCATION));
4469
4470 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004471 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004473 // 'notifyConnectionUnresponsive' should only be called once per connection
4474 mFakePolicy->assertNotifyAnrWasNotCalled();
4475 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476 mWindow->consumeMotionDown();
4477 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4478 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4479 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004480 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004481 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004482 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483}
4484
4485/**
4486 * If a window is processing a motion event, and then a key event comes in, the key event should
4487 * not to to the focused window until the motion is processed.
4488 *
4489 * Warning!!!
4490 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4491 * and the injection timeout that we specify when injecting the key.
4492 * We must have the injection timeout (10ms) be smaller than
4493 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4494 *
4495 * If that value changes, this test should also change.
4496 */
4497TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4498 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4500
4501 tapOnWindow();
4502 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4503 ASSERT_TRUE(downSequenceNum);
4504 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4505 ASSERT_TRUE(upSequenceNum);
4506 // Don't finish the events yet, and send a key
4507 // Injection will "succeed" because we will eventually give up and send the key to the focused
4508 // window even if motions are still being processed. But because the injection timeout is short,
4509 // we will receive INJECTION_TIMED_OUT as the result.
4510
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004511 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4514 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004515 // Key will not be sent to the window, yet, because the window is still processing events
4516 // and the key remains pending, waiting for the touch events to be processed
4517 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4518 ASSERT_FALSE(keySequenceNum);
4519
4520 std::this_thread::sleep_for(500ms);
4521 // if we wait long enough though, dispatcher will give up, and still send the key
4522 // to the focused window, even though we have not yet finished the motion event
4523 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4524 mWindow->finishEvent(*downSequenceNum);
4525 mWindow->finishEvent(*upSequenceNum);
4526}
4527
4528/**
4529 * If a window is processing a motion event, and then a key event comes in, the key event should
4530 * not go to the focused window until the motion is processed.
4531 * If then a new motion comes in, then the pending key event should be going to the currently
4532 * focused window right away.
4533 */
4534TEST_F(InputDispatcherSingleWindowAnr,
4535 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4536 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4538
4539 tapOnWindow();
4540 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4541 ASSERT_TRUE(downSequenceNum);
4542 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4543 ASSERT_TRUE(upSequenceNum);
4544 // Don't finish the events yet, and send a key
4545 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004547 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549 // At this point, key is still pending, and should not be sent to the application yet.
4550 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4551 ASSERT_FALSE(keySequenceNum);
4552
4553 // Now tap down again. It should cause the pending key to go to the focused window right away.
4554 tapOnWindow();
4555 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4556 // the other events yet. We can finish events in any order.
4557 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4558 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4559 mWindow->consumeMotionDown();
4560 mWindow->consumeMotionUp();
4561 mWindow->assertNoEvents();
4562}
4563
4564class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4565 virtual void SetUp() override {
4566 InputDispatcherTest::SetUp();
4567
Chris Yea209fde2020-07-22 13:54:51 -07004568 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569 mApplication->setDispatchingTimeout(10ms);
4570 mUnfocusedWindow =
4571 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4572 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4573 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4574 // window.
4575 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004576 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4577 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4578 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579
4580 mFocusedWindow =
4581 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004582 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004584 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585
4586 // Set focused application.
4587 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004588 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004589
4590 // Expect one focus window exist in display.
4591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004592 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593 mFocusedWindow->consumeFocusEvent(true);
4594 }
4595
4596 virtual void TearDown() override {
4597 InputDispatcherTest::TearDown();
4598
4599 mUnfocusedWindow.clear();
4600 mFocusedWindow.clear();
4601 }
4602
4603protected:
Chris Yea209fde2020-07-22 13:54:51 -07004604 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004605 sp<FakeWindowHandle> mUnfocusedWindow;
4606 sp<FakeWindowHandle> mFocusedWindow;
4607 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4608 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4609 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4610
4611 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4612
4613 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4614
4615private:
4616 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4619 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4622 location));
4623 }
4624};
4625
4626// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4627// should be ANR'd first.
4628TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4631 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004632 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004633 mFocusedWindow->consumeMotionDown();
4634 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4635 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4636 // We consumed all events, so no ANR
4637 ASSERT_TRUE(mDispatcher->waitForIdle());
4638 mFakePolicy->assertNotifyAnrWasNotCalled();
4639
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4642 FOCUSED_WINDOW_LOCATION));
4643 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4644 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645
4646 const std::chrono::duration timeout =
4647 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004648 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004649 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4650 // sequence to make it consistent
4651 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004653 mFocusedWindow->consumeMotionDown();
4654 // This cancel is generated because the connection was unresponsive
4655 mFocusedWindow->consumeMotionCancel();
4656 mFocusedWindow->assertNoEvents();
4657 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004658 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004659 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004660 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661}
4662
4663// If we have 2 windows with identical timeouts that are both unresponsive,
4664// it doesn't matter which order they should have ANR.
4665// But we should receive ANR for both.
4666TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4667 // Set the timeout for unfocused window to match the focused window
4668 mUnfocusedWindow->setDispatchingTimeout(10ms);
4669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4670
4671 tapOnFocusedWindow();
4672 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004673 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4674 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675
4676 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004677 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4678 mFocusedWindow->getToken() == anrConnectionToken2);
4679 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4680 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681
4682 ASSERT_TRUE(mDispatcher->waitForIdle());
4683 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004684
4685 mFocusedWindow->consumeMotionDown();
4686 mFocusedWindow->consumeMotionUp();
4687 mUnfocusedWindow->consumeMotionOutside();
4688
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004689 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4690 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004691
4692 // Both applications should be marked as responsive, in any order
4693 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4694 mFocusedWindow->getToken() == responsiveToken2);
4695 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4696 mUnfocusedWindow->getToken() == responsiveToken2);
4697 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698}
4699
4700// If a window is already not responding, the second tap on the same window should be ignored.
4701// We should also log an error to account for the dropped event (not tested here).
4702// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4703TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4704 tapOnFocusedWindow();
4705 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4706 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4707 // Receive the events, but don't respond
4708 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4709 ASSERT_TRUE(downEventSequenceNum);
4710 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4711 ASSERT_TRUE(upEventSequenceNum);
4712 const std::chrono::duration timeout =
4713 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004714 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004715
4716 // Tap once again
4717 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004718 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4720 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004721 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4723 FOCUSED_WINDOW_LOCATION));
4724 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4725 // valid touch target
4726 mUnfocusedWindow->assertNoEvents();
4727
4728 // Consume the first tap
4729 mFocusedWindow->finishEvent(*downEventSequenceNum);
4730 mFocusedWindow->finishEvent(*upEventSequenceNum);
4731 ASSERT_TRUE(mDispatcher->waitForIdle());
4732 // The second tap did not go to the focused window
4733 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004734 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004735 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736 mFakePolicy->assertNotifyAnrWasNotCalled();
4737}
4738
4739// If you tap outside of all windows, there will not be ANR
4740TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4743 LOCATION_OUTSIDE_ALL_WINDOWS));
4744 ASSERT_TRUE(mDispatcher->waitForIdle());
4745 mFakePolicy->assertNotifyAnrWasNotCalled();
4746}
4747
4748// Since the focused window is paused, tapping on it should not produce any events
4749TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4750 mFocusedWindow->setPaused(true);
4751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4755 FOCUSED_WINDOW_LOCATION));
4756
4757 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4758 ASSERT_TRUE(mDispatcher->waitForIdle());
4759 // Should not ANR because the window is paused, and touches shouldn't go to it
4760 mFakePolicy->assertNotifyAnrWasNotCalled();
4761
4762 mFocusedWindow->assertNoEvents();
4763 mUnfocusedWindow->assertNoEvents();
4764}
4765
4766/**
4767 * If a window is processing a motion event, and then a key event comes in, the key event should
4768 * not to to the focused window until the motion is processed.
4769 * If a different window becomes focused at this time, the key should go to that window instead.
4770 *
4771 * Warning!!!
4772 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4773 * and the injection timeout that we specify when injecting the key.
4774 * We must have the injection timeout (10ms) be smaller than
4775 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4776 *
4777 * If that value changes, this test should also change.
4778 */
4779TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4780 // Set a long ANR timeout to prevent it from triggering
4781 mFocusedWindow->setDispatchingTimeout(2s);
4782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4783
4784 tapOnUnfocusedWindow();
4785 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4786 ASSERT_TRUE(downSequenceNum);
4787 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4788 ASSERT_TRUE(upSequenceNum);
4789 // Don't finish the events yet, and send a key
4790 // Injection will succeed because we will eventually give up and send the key to the focused
4791 // window even if motions are still being processed.
4792
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004795 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 // Key will not be sent to the window, yet, because the window is still processing events
4798 // and the key remains pending, waiting for the touch events to be processed
4799 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4800 ASSERT_FALSE(keySequenceNum);
4801
4802 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004803 mFocusedWindow->setFocusable(false);
4804 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004806 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807
4808 // Focus events should precede the key events
4809 mUnfocusedWindow->consumeFocusEvent(true);
4810 mFocusedWindow->consumeFocusEvent(false);
4811
4812 // Finish the tap events, which should unblock dispatcher
4813 mUnfocusedWindow->finishEvent(*downSequenceNum);
4814 mUnfocusedWindow->finishEvent(*upSequenceNum);
4815
4816 // Now that all queues are cleared and no backlog in the connections, the key event
4817 // can finally go to the newly focused "mUnfocusedWindow".
4818 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4819 mFocusedWindow->assertNoEvents();
4820 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004821 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822}
4823
4824// When the touch stream is split across 2 windows, and one of them does not respond,
4825// then ANR should be raised and the touch should be canceled for the unresponsive window.
4826// The other window should not be affected by that.
4827TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4828 // Touch Window 1
4829 NotifyMotionArgs motionArgs =
4830 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4831 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4832 mDispatcher->notifyMotion(&motionArgs);
4833 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4834 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4835
4836 // Touch Window 2
4837 int32_t actionPointerDown =
4838 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4839
4840 motionArgs =
4841 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4842 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4843 mDispatcher->notifyMotion(&motionArgs);
4844
4845 const std::chrono::duration timeout =
4846 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004847 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848
4849 mUnfocusedWindow->consumeMotionDown();
4850 mFocusedWindow->consumeMotionDown();
4851 // Focused window may or may not receive ACTION_MOVE
4852 // But it should definitely receive ACTION_CANCEL due to the ANR
4853 InputEvent* event;
4854 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4855 ASSERT_TRUE(moveOrCancelSequenceNum);
4856 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4857 ASSERT_NE(nullptr, event);
4858 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4859 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4860 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4861 mFocusedWindow->consumeMotionCancel();
4862 } else {
4863 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4864 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004866 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004867
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868 mUnfocusedWindow->assertNoEvents();
4869 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004870 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004871}
4872
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004873/**
4874 * If we have no focused window, and a key comes in, we start the ANR timer.
4875 * The focused application should add a focused window before the timer runs out to prevent ANR.
4876 *
4877 * If the user touches another application during this time, the key should be dropped.
4878 * Next, if a new focused window comes in, without toggling the focused application,
4879 * then no ANR should occur.
4880 *
4881 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4882 * but in some cases the policy may not update the focused application.
4883 */
4884TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4885 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4886 std::make_shared<FakeApplicationHandle>();
4887 focusedApplication->setDispatchingTimeout(60ms);
4888 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4889 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4890 mFocusedWindow->setFocusable(false);
4891
4892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4893 mFocusedWindow->consumeFocusEvent(false);
4894
4895 // Send a key. The ANR timer should start because there is no focused window.
4896 // 'focusedApplication' will get blamed if this timer completes.
4897 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004899 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004900 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4901 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004903
4904 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4905 // then the injected touches won't cause the focused event to get dropped.
4906 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4907 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4908 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4909 // For this test, it means that the key would get delivered to the window once it becomes
4910 // focused.
4911 std::this_thread::sleep_for(10ms);
4912
4913 // Touch unfocused window. This should force the pending key to get dropped.
4914 NotifyMotionArgs motionArgs =
4915 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4916 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4917 mDispatcher->notifyMotion(&motionArgs);
4918
4919 // We do not consume the motion right away, because that would require dispatcher to first
4920 // process (== drop) the key event, and by that time, ANR will be raised.
4921 // Set the focused window first.
4922 mFocusedWindow->setFocusable(true);
4923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4924 setFocusedWindow(mFocusedWindow);
4925 mFocusedWindow->consumeFocusEvent(true);
4926 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4927 // to another application. This could be a bug / behaviour in the policy.
4928
4929 mUnfocusedWindow->consumeMotionDown();
4930
4931 ASSERT_TRUE(mDispatcher->waitForIdle());
4932 // Should not ANR because we actually have a focused window. It was just added too slowly.
4933 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4934}
4935
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004936// These tests ensure we cannot send touch events to a window that's positioned behind a window
4937// that has feature NO_INPUT_CHANNEL.
4938// Layout:
4939// Top (closest to user)
4940// mNoInputWindow (above all windows)
4941// mBottomWindow
4942// Bottom (furthest from user)
4943class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4944 virtual void SetUp() override {
4945 InputDispatcherTest::SetUp();
4946
4947 mApplication = std::make_shared<FakeApplicationHandle>();
4948 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4949 "Window without input channel", ADISPLAY_ID_DEFAULT,
4950 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4951
chaviw3277faf2021-05-19 16:45:23 -05004952 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004953 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4954 // It's perfectly valid for this window to not have an associated input channel
4955
4956 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4957 ADISPLAY_ID_DEFAULT);
4958 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4959
4960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4961 }
4962
4963protected:
4964 std::shared_ptr<FakeApplicationHandle> mApplication;
4965 sp<FakeWindowHandle> mNoInputWindow;
4966 sp<FakeWindowHandle> mBottomWindow;
4967};
4968
4969TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4970 PointF touchedPoint = {10, 10};
4971
4972 NotifyMotionArgs motionArgs =
4973 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4974 ADISPLAY_ID_DEFAULT, {touchedPoint});
4975 mDispatcher->notifyMotion(&motionArgs);
4976
4977 mNoInputWindow->assertNoEvents();
4978 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4979 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4980 // and therefore should prevent mBottomWindow from receiving touches
4981 mBottomWindow->assertNoEvents();
4982}
4983
4984/**
4985 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4986 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4987 */
4988TEST_F(InputDispatcherMultiWindowOcclusionTests,
4989 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4990 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4991 "Window with input channel and NO_INPUT_CHANNEL",
4992 ADISPLAY_ID_DEFAULT);
4993
chaviw3277faf2021-05-19 16:45:23 -05004994 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004995 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4997
4998 PointF touchedPoint = {10, 10};
4999
5000 NotifyMotionArgs motionArgs =
5001 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5002 ADISPLAY_ID_DEFAULT, {touchedPoint});
5003 mDispatcher->notifyMotion(&motionArgs);
5004
5005 mNoInputWindow->assertNoEvents();
5006 mBottomWindow->assertNoEvents();
5007}
5008
Vishnu Nair958da932020-08-21 17:12:37 -07005009class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5010protected:
5011 std::shared_ptr<FakeApplicationHandle> mApp;
5012 sp<FakeWindowHandle> mWindow;
5013 sp<FakeWindowHandle> mMirror;
5014
5015 virtual void SetUp() override {
5016 InputDispatcherTest::SetUp();
5017 mApp = std::make_shared<FakeApplicationHandle>();
5018 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5019 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5020 mWindow->getToken());
5021 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5022 mWindow->setFocusable(true);
5023 mMirror->setFocusable(true);
5024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5025 }
5026};
5027
5028TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5029 // Request focus on a mirrored window
5030 setFocusedWindow(mMirror);
5031
5032 // window gets focused
5033 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5035 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005036 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5037}
5038
5039// A focused & mirrored window remains focused only if the window and its mirror are both
5040// focusable.
5041TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5042 setFocusedWindow(mMirror);
5043
5044 // window gets focused
5045 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5047 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005048 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5050 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005051 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5052
5053 mMirror->setFocusable(false);
5054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5055
5056 // window loses focus since one of the windows associated with the token in not focusable
5057 mWindow->consumeFocusEvent(false);
5058
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005059 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5060 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005061 mWindow->assertNoEvents();
5062}
5063
5064// A focused & mirrored window remains focused until the window and its mirror both become
5065// invisible.
5066TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5067 setFocusedWindow(mMirror);
5068
5069 // window gets focused
5070 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5072 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005073 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5075 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005076 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5077
5078 mMirror->setVisible(false);
5079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005081 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5082 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005083 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5085 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005086 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5087
5088 mWindow->setVisible(false);
5089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5090
5091 // window loses focus only after all windows associated with the token become invisible.
5092 mWindow->consumeFocusEvent(false);
5093
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005094 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5095 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005096 mWindow->assertNoEvents();
5097}
5098
5099// A focused & mirrored window remains focused until both windows are removed.
5100TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5101 setFocusedWindow(mMirror);
5102
5103 // window gets focused
5104 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5106 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005107 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5109 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005110 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5111
5112 // single window is removed but the window token remains focused
5113 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5114
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5116 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005117 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5119 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005120 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5121
5122 // Both windows are removed
5123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5124 mWindow->consumeFocusEvent(false);
5125
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005126 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5127 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005128 mWindow->assertNoEvents();
5129}
5130
5131// Focus request can be pending until one window becomes visible.
5132TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5133 // Request focus on an invisible mirror.
5134 mWindow->setVisible(false);
5135 mMirror->setVisible(false);
5136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5137 setFocusedWindow(mMirror);
5138
5139 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005141 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005142 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005143
5144 mMirror->setVisible(true);
5145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5146
5147 // window gets focused
5148 mWindow->consumeFocusEvent(true);
5149 // window gets the pending key event
5150 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5151}
Prabir Pradhan99987712020-11-10 18:43:05 -08005152
5153class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5154protected:
5155 std::shared_ptr<FakeApplicationHandle> mApp;
5156 sp<FakeWindowHandle> mWindow;
5157 sp<FakeWindowHandle> mSecondWindow;
5158
5159 void SetUp() override {
5160 InputDispatcherTest::SetUp();
5161 mApp = std::make_shared<FakeApplicationHandle>();
5162 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5163 mWindow->setFocusable(true);
5164 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5165 mSecondWindow->setFocusable(true);
5166
5167 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5169
5170 setFocusedWindow(mWindow);
5171 mWindow->consumeFocusEvent(true);
5172 }
5173
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005174 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5175 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005176 mDispatcher->notifyPointerCaptureChanged(&args);
5177 }
5178
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005179 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5180 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005181 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005182 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5183 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005184 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005185 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005186 }
5187};
5188
5189TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5190 // Ensure that capture cannot be obtained for unfocused windows.
5191 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5192 mFakePolicy->assertSetPointerCaptureNotCalled();
5193 mSecondWindow->assertNoEvents();
5194
5195 // Ensure that capture can be enabled from the focus window.
5196 requestAndVerifyPointerCapture(mWindow, true);
5197
5198 // Ensure that capture cannot be disabled from a window that does not have capture.
5199 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5200 mFakePolicy->assertSetPointerCaptureNotCalled();
5201
5202 // Ensure that capture can be disabled from the window with capture.
5203 requestAndVerifyPointerCapture(mWindow, false);
5204}
5205
5206TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005207 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005208
5209 setFocusedWindow(mSecondWindow);
5210
5211 // Ensure that the capture disabled event was sent first.
5212 mWindow->consumeCaptureEvent(false);
5213 mWindow->consumeFocusEvent(false);
5214 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005215 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005216
5217 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005218 notifyPointerCaptureChanged({});
5219 notifyPointerCaptureChanged(request);
5220 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005221 mWindow->assertNoEvents();
5222 mSecondWindow->assertNoEvents();
5223 mFakePolicy->assertSetPointerCaptureNotCalled();
5224}
5225
5226TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005227 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005228
5229 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005230 notifyPointerCaptureChanged({});
5231 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005232
5233 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005234 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005235 mWindow->consumeCaptureEvent(false);
5236 mWindow->assertNoEvents();
5237}
5238
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005239TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5240 requestAndVerifyPointerCapture(mWindow, true);
5241
5242 // The first window loses focus.
5243 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005244 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005245 mWindow->consumeCaptureEvent(false);
5246
5247 // Request Pointer Capture from the second window before the notification from InputReader
5248 // arrives.
5249 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005250 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005251
5252 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005253 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005254
5255 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005256 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005257
5258 mSecondWindow->consumeFocusEvent(true);
5259 mSecondWindow->consumeCaptureEvent(true);
5260}
5261
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005262TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5263 // App repeatedly enables and disables capture.
5264 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5265 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5266 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5267 mFakePolicy->assertSetPointerCaptureCalled(false);
5268 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5269 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5270
5271 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5272 // first request is now stale, this should do nothing.
5273 notifyPointerCaptureChanged(firstRequest);
5274 mWindow->assertNoEvents();
5275
5276 // InputReader notifies that the second request was enabled.
5277 notifyPointerCaptureChanged(secondRequest);
5278 mWindow->consumeCaptureEvent(true);
5279}
5280
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005281class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5282protected:
5283 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005284
5285 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5286 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5287
5288 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5289 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5290
5291 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5292 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5293 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5294 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5295 MAXIMUM_OBSCURING_OPACITY);
5296
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005297 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005298 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005299 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005300
5301 sp<FakeWindowHandle> mTouchWindow;
5302
5303 virtual void SetUp() override {
5304 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005305 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005306 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5307 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5308 }
5309
5310 virtual void TearDown() override {
5311 InputDispatcherTest::TearDown();
5312 mTouchWindow.clear();
5313 }
5314
chaviw3277faf2021-05-19 16:45:23 -05005315 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5316 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005317 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005318 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005319 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005320 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005321 return window;
5322 }
5323
5324 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5325 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5326 sp<FakeWindowHandle> window =
5327 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5328 // Generate an arbitrary PID based on the UID
5329 window->setOwnerInfo(1777 + (uid % 10000), uid);
5330 return window;
5331 }
5332
5333 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5334 NotifyMotionArgs args =
5335 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5336 ADISPLAY_ID_DEFAULT, points);
5337 mDispatcher->notifyMotion(&args);
5338 }
5339};
5340
5341TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005342 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005343 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005345
5346 touch();
5347
5348 mTouchWindow->assertNoEvents();
5349}
5350
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005351TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005352 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5353 const sp<FakeWindowHandle>& w =
5354 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5356
5357 touch();
5358
5359 mTouchWindow->assertNoEvents();
5360}
5361
5362TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005363 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5364 const sp<FakeWindowHandle>& w =
5365 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5367
5368 touch();
5369
5370 w->assertNoEvents();
5371}
5372
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005373TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005374 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005376
5377 touch();
5378
5379 mTouchWindow->consumeAnyMotionDown();
5380}
5381
5382TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005383 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005384 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005385 w->setFrame(Rect(0, 0, 50, 50));
5386 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005387
5388 touch({PointF{100, 100}});
5389
5390 mTouchWindow->consumeAnyMotionDown();
5391}
5392
5393TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005394 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005395 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5397
5398 touch();
5399
5400 mTouchWindow->consumeAnyMotionDown();
5401}
5402
5403TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5404 const sp<FakeWindowHandle>& w =
5405 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5406 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005407
5408 touch();
5409
5410 mTouchWindow->consumeAnyMotionDown();
5411}
5412
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005413TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5414 const sp<FakeWindowHandle>& w =
5415 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5417
5418 touch();
5419
5420 w->assertNoEvents();
5421}
5422
5423/**
5424 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5425 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5426 * window, the occluding window will still receive ACTION_OUTSIDE event.
5427 */
5428TEST_F(InputDispatcherUntrustedTouchesTest,
5429 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5430 const sp<FakeWindowHandle>& w =
5431 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005432 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5434
5435 touch();
5436
5437 w->consumeMotionOutside();
5438}
5439
5440TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5441 const sp<FakeWindowHandle>& w =
5442 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005443 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5445
5446 touch();
5447
5448 InputEvent* event = w->consume();
5449 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5450 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5451 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5452 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5453}
5454
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005455TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005456 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005457 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5458 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5460
5461 touch();
5462
5463 mTouchWindow->consumeAnyMotionDown();
5464}
5465
5466TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5467 const sp<FakeWindowHandle>& w =
5468 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5469 MAXIMUM_OBSCURING_OPACITY);
5470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005471
5472 touch();
5473
5474 mTouchWindow->consumeAnyMotionDown();
5475}
5476
5477TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005478 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005479 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5480 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5482
5483 touch();
5484
5485 mTouchWindow->assertNoEvents();
5486}
5487
5488TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5489 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5490 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005491 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5492 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005493 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005494 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5495 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5497
5498 touch();
5499
5500 mTouchWindow->assertNoEvents();
5501}
5502
5503TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5504 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5505 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005506 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5507 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005508 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005509 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5510 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5512
5513 touch();
5514
5515 mTouchWindow->consumeAnyMotionDown();
5516}
5517
5518TEST_F(InputDispatcherUntrustedTouchesTest,
5519 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5520 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005521 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5522 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005523 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005524 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5525 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5527
5528 touch();
5529
5530 mTouchWindow->consumeAnyMotionDown();
5531}
5532
5533TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5534 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005535 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5536 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005537 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005538 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5539 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005541
5542 touch();
5543
5544 mTouchWindow->assertNoEvents();
5545}
5546
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005547TEST_F(InputDispatcherUntrustedTouchesTest,
5548 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5549 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005550 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5551 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005552 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005553 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5554 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5556
5557 touch();
5558
5559 mTouchWindow->assertNoEvents();
5560}
5561
5562TEST_F(InputDispatcherUntrustedTouchesTest,
5563 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5564 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005565 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5566 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005567 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005568 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5569 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5571
5572 touch();
5573
5574 mTouchWindow->consumeAnyMotionDown();
5575}
5576
5577TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5578 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005579 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5580 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5582
5583 touch();
5584
5585 mTouchWindow->consumeAnyMotionDown();
5586}
5587
5588TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5589 const sp<FakeWindowHandle>& w =
5590 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5592
5593 touch();
5594
5595 mTouchWindow->consumeAnyMotionDown();
5596}
5597
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005598TEST_F(InputDispatcherUntrustedTouchesTest,
5599 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5600 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5601 const sp<FakeWindowHandle>& w =
5602 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5604
5605 touch();
5606
5607 mTouchWindow->assertNoEvents();
5608}
5609
5610TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5611 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5612 const sp<FakeWindowHandle>& w =
5613 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5615
5616 touch();
5617
5618 mTouchWindow->consumeAnyMotionDown();
5619}
5620
5621TEST_F(InputDispatcherUntrustedTouchesTest,
5622 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5623 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5624 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005625 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5626 OPACITY_ABOVE_THRESHOLD);
5627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5628
5629 touch();
5630
5631 mTouchWindow->consumeAnyMotionDown();
5632}
5633
5634TEST_F(InputDispatcherUntrustedTouchesTest,
5635 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5636 const sp<FakeWindowHandle>& w1 =
5637 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5638 OPACITY_BELOW_THRESHOLD);
5639 const sp<FakeWindowHandle>& w2 =
5640 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5641 OPACITY_BELOW_THRESHOLD);
5642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5643
5644 touch();
5645
5646 mTouchWindow->assertNoEvents();
5647}
5648
5649/**
5650 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5651 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5652 * (which alone would result in allowing touches) does not affect the blocking behavior.
5653 */
5654TEST_F(InputDispatcherUntrustedTouchesTest,
5655 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5656 const sp<FakeWindowHandle>& wB =
5657 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5658 OPACITY_BELOW_THRESHOLD);
5659 const sp<FakeWindowHandle>& wC =
5660 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5661 OPACITY_BELOW_THRESHOLD);
5662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5663
5664 touch();
5665
5666 mTouchWindow->assertNoEvents();
5667}
5668
5669/**
5670 * This test is testing that a window from a different UID but with same application token doesn't
5671 * block the touch. Apps can share the application token for close UI collaboration for example.
5672 */
5673TEST_F(InputDispatcherUntrustedTouchesTest,
5674 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5675 const sp<FakeWindowHandle>& w =
5676 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5677 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5679
5680 touch();
5681
5682 mTouchWindow->consumeAnyMotionDown();
5683}
5684
arthurhungb89ccb02020-12-30 16:19:01 +08005685class InputDispatcherDragTests : public InputDispatcherTest {
5686protected:
5687 std::shared_ptr<FakeApplicationHandle> mApp;
5688 sp<FakeWindowHandle> mWindow;
5689 sp<FakeWindowHandle> mSecondWindow;
5690 sp<FakeWindowHandle> mDragWindow;
5691
5692 void SetUp() override {
5693 InputDispatcherTest::SetUp();
5694 mApp = std::make_shared<FakeApplicationHandle>();
5695 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5696 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005697 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005698
5699 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5700 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005701 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005702
5703 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5705 }
5706
5707 // Start performing drag, we will create a drag window and transfer touch to it.
5708 void performDrag() {
5709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5710 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5711 {50, 50}))
5712 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5713
5714 // Window should receive motion event.
5715 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5716
5717 // The drag window covers the entire display
5718 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5719 mDispatcher->setInputWindows(
5720 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5721
5722 // Transfer touch focus to the drag window
5723 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5724 true /* isDragDrop */);
5725 mWindow->consumeMotionCancel();
5726 mDragWindow->consumeMotionDown();
5727 }
arthurhung6d4bed92021-03-17 11:59:33 +08005728
5729 // Start performing drag, we will create a drag window and transfer touch to it.
5730 void performStylusDrag() {
5731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5732 injectMotionEvent(mDispatcher,
5733 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5734 AINPUT_SOURCE_STYLUS)
5735 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5736 .pointer(PointerBuilder(0,
5737 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5738 .x(50)
5739 .y(50))
5740 .build()));
5741 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5742
5743 // The drag window covers the entire display
5744 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5745 mDispatcher->setInputWindows(
5746 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5747
5748 // Transfer touch focus to the drag window
5749 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5750 true /* isDragDrop */);
5751 mWindow->consumeMotionCancel();
5752 mDragWindow->consumeMotionDown();
5753 }
arthurhungb89ccb02020-12-30 16:19:01 +08005754};
5755
5756TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5757 performDrag();
5758
5759 // Move on window.
5760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5761 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5762 ADISPLAY_ID_DEFAULT, {50, 50}))
5763 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5764 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5765 mWindow->consumeDragEvent(false, 50, 50);
5766 mSecondWindow->assertNoEvents();
5767
5768 // Move to another window.
5769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5770 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5771 ADISPLAY_ID_DEFAULT, {150, 50}))
5772 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5773 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5774 mWindow->consumeDragEvent(true, 150, 50);
5775 mSecondWindow->consumeDragEvent(false, 50, 50);
5776
5777 // Move back to original window.
5778 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5779 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5780 ADISPLAY_ID_DEFAULT, {50, 50}))
5781 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5782 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5783 mWindow->consumeDragEvent(false, 50, 50);
5784 mSecondWindow->consumeDragEvent(true, -50, 50);
5785
5786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5787 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5789 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5790 mWindow->assertNoEvents();
5791 mSecondWindow->assertNoEvents();
5792}
5793
arthurhungf452d0b2021-01-06 00:19:52 +08005794TEST_F(InputDispatcherDragTests, DragAndDrop) {
5795 performDrag();
5796
5797 // Move on window.
5798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5799 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5800 ADISPLAY_ID_DEFAULT, {50, 50}))
5801 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5802 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5803 mWindow->consumeDragEvent(false, 50, 50);
5804 mSecondWindow->assertNoEvents();
5805
5806 // Move to another window.
5807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5808 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5809 ADISPLAY_ID_DEFAULT, {150, 50}))
5810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5811 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5812 mWindow->consumeDragEvent(true, 150, 50);
5813 mSecondWindow->consumeDragEvent(false, 50, 50);
5814
5815 // drop to another window.
5816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5817 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5818 {150, 50}))
5819 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5820 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5821 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5822 mWindow->assertNoEvents();
5823 mSecondWindow->assertNoEvents();
5824}
5825
arthurhung6d4bed92021-03-17 11:59:33 +08005826TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5827 performStylusDrag();
5828
5829 // Move on window and keep button pressed.
5830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5831 injectMotionEvent(mDispatcher,
5832 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5833 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5834 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5835 .x(50)
5836 .y(50))
5837 .build()))
5838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5839 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5840 mWindow->consumeDragEvent(false, 50, 50);
5841 mSecondWindow->assertNoEvents();
5842
5843 // Move to another window and release button, expect to drop item.
5844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5845 injectMotionEvent(mDispatcher,
5846 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5847 .buttonState(0)
5848 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5849 .x(150)
5850 .y(50))
5851 .build()))
5852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5853 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5854 mWindow->assertNoEvents();
5855 mSecondWindow->assertNoEvents();
5856 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5857
5858 // nothing to the window.
5859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5860 injectMotionEvent(mDispatcher,
5861 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5862 .buttonState(0)
5863 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5864 .x(150)
5865 .y(50))
5866 .build()))
5867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5868 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5869 mWindow->assertNoEvents();
5870 mSecondWindow->assertNoEvents();
5871}
5872
Arthur Hung6d0571e2021-04-09 20:18:16 +08005873TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5874 performDrag();
5875
5876 // Set second window invisible.
5877 mSecondWindow->setVisible(false);
5878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5879
5880 // Move on window.
5881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5882 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5883 ADISPLAY_ID_DEFAULT, {50, 50}))
5884 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5885 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5886 mWindow->consumeDragEvent(false, 50, 50);
5887 mSecondWindow->assertNoEvents();
5888
5889 // Move to another window.
5890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5891 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5892 ADISPLAY_ID_DEFAULT, {150, 50}))
5893 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5894 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5895 mWindow->consumeDragEvent(true, 150, 50);
5896 mSecondWindow->assertNoEvents();
5897
5898 // drop to another window.
5899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5900 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5901 {150, 50}))
5902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5903 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5904 mFakePolicy->assertDropTargetEquals(nullptr);
5905 mWindow->assertNoEvents();
5906 mSecondWindow->assertNoEvents();
5907}
5908
Vishnu Nair062a8672021-09-03 16:07:44 -07005909class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5910
5911TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5912 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5913 sp<FakeWindowHandle> window =
5914 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5915 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5916 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5917 window->setFocusable(true);
5918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5919 setFocusedWindow(window);
5920 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5921
5922 // With the flag set, window should not get any input
5923 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5924 mDispatcher->notifyKey(&keyArgs);
5925 window->assertNoEvents();
5926
5927 NotifyMotionArgs motionArgs =
5928 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5929 ADISPLAY_ID_DEFAULT);
5930 mDispatcher->notifyMotion(&motionArgs);
5931 window->assertNoEvents();
5932
5933 // With the flag cleared, the window should get input
5934 window->setInputFeatures({});
5935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5936
5937 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5938 mDispatcher->notifyKey(&keyArgs);
5939 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5940
5941 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5942 ADISPLAY_ID_DEFAULT);
5943 mDispatcher->notifyMotion(&motionArgs);
5944 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5945 window->assertNoEvents();
5946}
5947
5948TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5949 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5950 std::make_shared<FakeApplicationHandle>();
5951 sp<FakeWindowHandle> obscuringWindow =
5952 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5953 ADISPLAY_ID_DEFAULT);
5954 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5955 obscuringWindow->setOwnerInfo(111, 111);
5956 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5957 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5958 sp<FakeWindowHandle> window =
5959 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5960 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5961 window->setOwnerInfo(222, 222);
5962 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5963 window->setFocusable(true);
5964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5965 setFocusedWindow(window);
5966 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5967
5968 // With the flag set, window should not get any input
5969 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5970 mDispatcher->notifyKey(&keyArgs);
5971 window->assertNoEvents();
5972
5973 NotifyMotionArgs motionArgs =
5974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5975 ADISPLAY_ID_DEFAULT);
5976 mDispatcher->notifyMotion(&motionArgs);
5977 window->assertNoEvents();
5978
5979 // With the flag cleared, the window should get input
5980 window->setInputFeatures({});
5981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5982
5983 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5984 mDispatcher->notifyKey(&keyArgs);
5985 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5986
5987 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5988 ADISPLAY_ID_DEFAULT);
5989 mDispatcher->notifyMotion(&motionArgs);
5990 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5991 window->assertNoEvents();
5992}
5993
5994TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5995 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5996 std::make_shared<FakeApplicationHandle>();
5997 sp<FakeWindowHandle> obscuringWindow =
5998 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5999 ADISPLAY_ID_DEFAULT);
6000 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6001 obscuringWindow->setOwnerInfo(111, 111);
6002 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6003 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6004 sp<FakeWindowHandle> window =
6005 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6006 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6007 window->setOwnerInfo(222, 222);
6008 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6009 window->setFocusable(true);
6010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6011 setFocusedWindow(window);
6012 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6013
6014 // With the flag set, window should not get any input
6015 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6016 mDispatcher->notifyKey(&keyArgs);
6017 window->assertNoEvents();
6018
6019 NotifyMotionArgs motionArgs =
6020 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6021 ADISPLAY_ID_DEFAULT);
6022 mDispatcher->notifyMotion(&motionArgs);
6023 window->assertNoEvents();
6024
6025 // When the window is no longer obscured because it went on top, it should get input
6026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6027
6028 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6029 mDispatcher->notifyKey(&keyArgs);
6030 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6031
6032 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6033 ADISPLAY_ID_DEFAULT);
6034 mDispatcher->notifyMotion(&motionArgs);
6035 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6036 window->assertNoEvents();
6037}
6038
Antonio Kantekf16f2832021-09-28 04:39:20 +00006039class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6040protected:
6041 std::shared_ptr<FakeApplicationHandle> mApp;
6042 sp<FakeWindowHandle> mWindow;
6043 sp<FakeWindowHandle> mSecondWindow;
6044
6045 void SetUp() override {
6046 InputDispatcherTest::SetUp();
6047
6048 mApp = std::make_shared<FakeApplicationHandle>();
6049 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6050 mWindow->setFocusable(true);
6051 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6052 mSecondWindow->setFocusable(true);
6053
6054 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6056
6057 setFocusedWindow(mWindow);
6058 mWindow->consumeFocusEvent(true);
6059 }
6060
6061 void changeAndVerifyTouchMode(bool inTouchMode) {
6062 mDispatcher->setInTouchMode(inTouchMode);
6063 mWindow->consumeTouchModeEvent(inTouchMode);
6064 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6065 }
6066};
6067
6068TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6069 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6070}
6071
6072TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6073 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6074 mWindow->assertNoEvents();
6075 mSecondWindow->assertNoEvents();
6076}
6077
Garfield Tane84e6f92019-08-29 17:28:41 -07006078} // namespace android::inputdispatcher